Yii - Konfigurationen

Konfigurationen werden verwendet, um neue Objekte zu erstellen oder vorhandene zu initialisieren. Konfigurationen enthalten normalerweise einen Klassennamen und eine Liste von Anfangswerten. Sie können auch eine Liste von Ereignishandlern und Verhaltensweisen enthalten.

Das folgende Beispiel zeigt die Datenbankkonfiguration:

<?php
   $config = [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host = localhost;dbname = helloworld',
      'username' => 'vladimir',
      'password' => '12345',
      'charset' => 'utf8',
   ];
   $db = Yii::createObject($config);
?>

Das Yii::createObject() Die Methode verwendet ein Konfigurationsarray und erstellt ein Objekt basierend auf der in der Konfiguration genannten Klasse.

Das Format einer Konfiguration -

[
   //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,
]

Die Konfigurationsdatei einer grundlegenden Anwendungsvorlage ist eine der komplexesten -

<?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' => 'ymoaYrebZHa8gURuolioHGlK8fLXCKjO',
         ],
         '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' => [
         'hello' => [
            'class' => 'app\modules\hello\Hello',
         ],
      ],
      '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;
?>

In der obigen Konfigurationsdatei definieren wir den Klassennamen nicht. Dies liegt daran, dass wir es bereits in der definiert habenindex.php Datei -

<?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();
?>

Viele Widgets verwenden auch Konfigurationen, wie im folgenden Code gezeigt.

<?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();
?>

Wenn eine Konfiguration zu komplex ist, wird häufig eine PHP-Datei erstellt, die ein Array zurückgibt. Schauen Sie sich das anconfig/console.php Konfigurationsdatei -

<?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,
   ];
?>

Die Standardkonfigurationen können durch Aufrufen von angegeben werden Yii::$container->set()Methode. Sie können Standardkonfigurationen auf alle Instanzen der angegebenen Klassen anwenden, wenn diese über das aufgerufen werdenYii::createObject() Methode.

Zum Beispiel, um die anzupassen yii\widgets\LinkPager Klasse, so dass alle Link-Pager höchstens drei Schaltflächen anzeigen, können Sie den folgenden Code verwenden.

\Yii::$container->set('yii\widgets\LinkPager', [
   'maxButtonCount' => 3,
]);