Yii組態


組態用於建立新的物件或初始化現有的物件。構通常包括一個類名稱和初始值的列表。它們還可以包括事件處理程式和行為的列表。
以下是資料庫組態的一個例子(在之前的例子中我們已經接觸了) -
<?php
   $config = [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host = localhost;dbname = mystudy',
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
   ];
   $db = Yii::createObject($config);
?>
在 Yii::createObject() 方法需要一個組態陣列,並基於組態類的名稱來建立物件。
組態的格式如下 -
[
   //a fully qualified class name for the object being created
   'class' => 'ClassName',
   //initial values for the named property
   'propertyName' => 'propertyValue',
   //specifies what handlers should be attached to the object's events
   'on eventName' => $eventHandler,
   //specifies what behaviors should be attached to the object
   'as behaviorName' => $behaviorConfig,
]
一個基本的應用程式模板的組態檔案是組成複雜組態的一個小部分 -
<?php
   $params = require(__DIR__ . '/params.php');
   $config = [
      'id' => 'basic',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log'],
      'components' => [
         'request' => [
            // !!! insert a secret key in the following (if it is empty) - this 
               //is required by cookie validation
            'cookieValidationKey' => 'yfajskldfTw511.com89dfad.dfasd#',
         ],
         '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'],
               ],
            ],
         ],
         'urlManager' => [
            //'showScriptName' => false,
            //'enablePrettyUrl' => true,
            //'enableStrictParsing' => true,
            //'suffix' => '/'
         ],
         '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;
?>
在上面的組態檔案,我們沒有定義類名。這是因為我們已經在 index.php 檔案中定義它了 -
<?php
   //defining global constans
   defined('YII_DEBUG') or define('YII_DEBUG', true);
   defined('YII_ENV') or define('YII_ENV', 'dev');
   //register composer autoloader
   require(__DIR__ . '/../vendor/autoload.php');
   //include yii files
   require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
   //load application config
   $config = require(__DIR__ . '/../config/web.php');
   //create, config, and process request
   (new yii\web\Application($config))->run();
?>
許多小部件也使用組態,如下面的程式碼中所示。
<?php
   NavBar::begin([
      'brandLabel' => 'My Company',
      'brandUrl' => Yii::$app->homeUrl,
      'options' => [
         'class' => 'navbar-inverse navbar-fixed-top',
      ],
   ]);
   echo Nav::widget([
      'options' => ['class' => 'navbar-nav navbar-right'],
      'items' => [
         ['label' => 'Home', 'url' => ['/site/index']],
         ['label' => 'About', 'url' => ['/site/about']],
         ['label' => 'Contact', 'url' => ['/site/contact']],
         Yii::$app->user->isGuest ?
         ['label' => 'Login', 'url' => ['/site/login']] :
         [
            'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
            'url' => ['/site/logout'],
            'linkOptions' => ['data-method' => 'post']
         ],
      ],
   ]);
   NavBar::end();
?>
當組態過於複雜,常見的做法是建立一個新的 PHP 檔案,其中讓它返回一個陣列。看看 config/console.php 組態檔案就知道了 -
<?php
   Yii::setAlias('@tests', dirname(__DIR__) . '/tests');

   $params = require(__DIR__ . '/params.php');
   $db = require(__DIR__ . '/db.php');

   return [
      'id' => 'basic-console',
      'basePath' => dirname(__DIR__),
      'bootstrap' => ['log', 'gii'],
      'controllerNamespace' => 'app\commands',
      'modules' => [
         'gii' => 'yii\gii\Module',
      ],
      'components' => [
         'cache' => [
            'class' => 'yii\caching\FileCache',
         ],
         'log' => [
            'targets' => [
               [
                  'class' => 'yii\log\FileTarget',
                  'levels' => ['error', 'warning'],
               ],
            ],
         ],
         'db' => $db,
      ],
      'params' => $params,
   ];
?>
預設組態可以通過呼叫 Yii::$container->set() 方法來指定。通過 Yii::CreateObject()方法呼叫它可以為應用建立預設組態指定的那些類的所有範例。
例如,自定義 yii\widgets\LinkPager 類,這樣所有連結頁面將顯示最多三個按鈕,使用如下程式碼。
\Yii::$container->set('yii\widgets\LinkPager', [
   'maxButtonCount' => 3,
]);