Yii資源(Asset)

資源(asset)是一個檔,該檔可在網頁中被引用(CSS,JS,視頻,音頻或圖像等)。Yii使用資源包管理asset. 資產包的目的是要有一組代碼庫關聯JS或CSS檔,並能夠在一個單一的PHP調用中註冊。資源包還依懶於其他資源包。
在assets檔夾裏面,可找到基本的應用程式範本資源包-
<?php
   namespace app\assets;
   use yii\web\AssetBundle;
   /**
   * @author Qiang Xue <qiang.xue@gmail.com>
   * @since 2.0
   */
   class AppAsset extends AssetBundle {
      public $basePath = '@webroot';
      public $baseUrl = '@web';
      public $css = [
         'css/site.css',
      ];
      public $js = [];
      public $depends = [
         'yii\web\YiiAsset',
         'yii\bootstrap\BootstrapAsset',
      ];
   }
?> 

上述類指定資源檔位於 @webroot 檔夾中,其對應於URL @web 。 此資源包不包含 JS 檔和 CSS 檔。該包依賴於其他包-

yii\web\YiiAsset 和 yii\bootstrap\BootstrapAsset

AssetBundle的屬性

以下是資源包的屬性。
  • basePath − 定義在此捆綁包包含資源檔的Web訪問目錄。

  • baseUrl − 指定對應於根路徑屬性的URL

  • js − 定義包含在此捆綁包的JS檔數組

  • css − 定義包含在這個捆綁包的CSS檔數組

  • depends − 定義了該包依賴於資源包數組。這意味著,當前資源包的CSS和JS檔將被包括在資源包,這是取決於屬性聲明之後。

  • sourcePath − 定義包含資源檔的根目錄。如果根目錄不是通過Web訪問,應該要設置這個屬性。

    否則應該設置basePath和baseUrl屬性。
  • cssOptions − 定義選項將傳遞到 yii\web\View∷registerCssFile 函數

  • jsOptions − 定義的選項被傳遞到 yii\web\View::registerJsFile 函數

  • publishOptions: 指定選項將被傳遞到yii\web\AssetManager::publish 函數

資源的分類

根據位置,assets 可以被歸類為-
  • Source Assets − assets是位於無法通過網路直接訪問的目錄。在頁面使用源資源應該被複製到網站目錄。

    這個過程被稱為資源發佈。
  • Published Assets − 該 assets 為位於一個Web訪問的目錄

  • External Assets − 該 assets 位於另一臺Web伺服器上。

使用資源包

第1步 - 在 assets 檔夾裏面創建一個名為 DemoAsset.php 的新檔包含以下內容。
<?php
   namespace app\assets;
   use yii\web\AssetBundle;
   class DemoAsset extends AssetBundle {
      public $basePath = '@webroot';
      public $baseUrl = '@web';
      public $js = ['js/demo.js'];
   }
?> 

第2步 - 聲明一個demo.js檔的新資源包。現在,在 web/js 檔夾中,創建一個名為 demo.js 檔並使用以下代碼。

console.log("hello from Demo asset");
第3步 - 要註冊新創建的資源包,轉到 views/layouts 目錄,並在 main.php 檔的頂部,添加以下行。
\app\assets\DemoAsset::register($this);
第4步 - 如果在Web流覽器中打開URL:http://localhost:8080/index.php,你應該看到下麵的 chrome 控制臺輸出。

還可以定義jsOptions和cssOptions屬性來定制該CSS和JS檔包含在一頁面。 默認情況下,JS檔包括在結束標記之前。

步驟5 - 在JS檔包函在頭部分,使用以下列方式修改 DemoAsset.php 檔。
<?php
   namespace app\assets;
   use yii\web\AssetBundle;
   use yii\web\View;
   class DemoAsset extends AssetBundle {
      public $basePath = '@webroot';
      public $baseUrl = '@web';
      public $js = ['js/demo.js'];
      public  $jsOptions = ['position' => View::POS_HEAD];
   }
?>
第6步 - 現在進入到 http://localhost:8080/index.php,應該看到 demo.js 腳本包含在頁面的 head 部分。

這是一個Web應用程式的普遍做法,在生產模式下運行,以使HTTP緩存 assets 資源。通過這樣做,最近修改的時間戳將被附加到所有已發佈的 assets 資源。

第7步 - 轉到 config/web.php 並修改檔web.php,如下面的代碼。
<?php
   $params = require(__DIR__ . '/params.php');
   $config = [
      'id' => 'basic',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log'],
      'components' => [
         'assetManager' => [
            'appendTimestamp' => true,
         ],
         'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is
               //required by cookie validation
            'cookieValidationKey' => 'xuhuhu.com',
         ],
         'cache' => [
            'class' => 'yii\caching\FileCache',
         ],
         'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
         ],
         'errorHandler' => [
            'errorAction' => 'site/error',
         ],
         'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
         ],
         'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
               [
                  'class' => 'yii\log\FileTarget',
                  'levels' => ['error', 'warning'],
               ],
            ],
         ],
         'db' => require(__DIR__ . '/db.php'),
      ],
      'modules' => [
         'admin' => [
            'class' => 'app\modules\admin\Admin',
         ],
      ],
      'params' => $params,
   ];
   if (YII_ENV_DEV) {
      // configuration adjustments for 'dev' environment
      $config['bootstrap'][] = 'debug';
      $config['modules']['debug'] = [
         'class' => 'yii\debug\Module',
      ];
      $config['bootstrap'][] = 'gii';
      $config['modules']['gii'] = [
         'class' => 'yii\gii\Module',
      ];
   }
   return $config;
?>
我們已經增加了AssetManager 組件,並設置 appendTimestamp 屬性。

第8步,在Web流覽器的地址欄中輸入: http://localhost:8080/index.php 。你會發現,所有的 assets 資源現在有一個時間戳,如下面的圖片所示。

Yii的核心Assetbundles

以下是 Yii 核心Assetbundles
  • yii\web\JqueryAsset − 包含 jquery.js 檔

  • yii\web\YiiAsset − 包含yii.js檔,它實現在模組組織JS代碼的機制

  • yii\bootstrap\BootstrapAsset − 包含yii.js檔,它在模組組織實現JS代碼的機制

  • yii\bootstrap\BootstrapPluginAsset − 包函來自Twitter Bootstrap 框架JS檔

  • yii\jui\JuiAsset − 包括 jQuery UI庫中的CSS和JS檔


上一篇: Yii佈局(Layouts) 下一篇: Yii Asset轉換