Yii Tutorial on Yii Configurations

configurations are used to create new objects or initializing the existing ones. configurations usually include a class name and a list of initial values. they may also include a list of event handlers and behaviors.

the following is an example of the database configuration −

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

the yii::createobject() method takes a configuration array and creates an object based on the class named in the configuration.

the format of a configuration −

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

the configuration file of a basic application template is one of the most complex −

<?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 the above configuration file, we do not define the class name. this is because we have already defined it in the index.php file −

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

many widgets also use configurations as shown in the following code.

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

when a configuration is too complex, a common practice is to create a php file, which returns an array. take a look at the config/console.php configuration file −

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

the default configurations can be specified by calling the yii::$container->set() method. it allows you to apply default configurations to all instances of the specified classes when they are called via the yii::createobject() method.

for example, to customize the yii\widgets\linkpager class, so that all link pagers will show at most three buttons, you can use the following code.

\yii::$container->set('yii\widgets\linkpager', [
   'maxbuttoncount' => 3,
]);