Configure | core architecture | Yii Chinese document 2.0.x

Posted by jbingman on Sat, 05 Feb 2022 10:26:04 +0100

Configurations

In Yii, configuration is widely used when creating new objects and initializing existing objects. The configuration usually contains the class name of the created object and a set of objects to be assigned attribute Initial value of. It may also contain a set of objects to be attached to event Handle on. And a set of objects to be attached to behavior.

The configuration in the following code is used to create and initialize a database connection:

$config = [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];

$db = Yii::createObject($config);

The [[Yii::createObject()]] method accepts a configuration array and creates an object according to the class name specified in the array. After the object is instantiated, the remaining parameters are used to initialize the object's properties, event handling and behavior.

For existing objects, you can use the [[Yii::configure()]] method to initialize their properties according to the configuration, as follows:

Yii::configure($object, $config);

Note that if you configure an existing object, the configuration array should not contain the class element with the specified class name.

Configuration format

The format of a configuration can be described as follows:

[
    'class' => 'ClassName',
    'propertyName' => 'propertyValue',
    'on eventName' => $eventHandler,
    'as behaviorName' => $behaviorConfig,
]

among

  • The class element specifies the fully qualified class name of the object to be created.
  • The propertyName element specifies the initial value of the object property. The key name is the property name, and the value is the initial value corresponding to the property. Only public member variables and variables defined through getter/setter attribute Can be configured.
  • The on eventName element specifies an object to attach to event What is the handle on the. Note that the key name of the array consists of the on prefix plus the event name. Please refer to event This section describes the format of event handles.
  • The as behaviorName element specifies the name attached to the object behavior . Note that the key name of the array consists of the as prefix plus the behavior name$ The behaviorConfig value represents the configuration information of the creation behavior, and the format is the same as that described earlier.

The following is an example with initialization attribute values, event handles and behaviors configured:

[
    'class' => 'app\components\SearchEngine',
    'apiKey' => 'xxxxxxxx',
    'on search' => function ($event) {
        Yii::info("Keywords to search: " . $event->keyword);
    },
    'as indexer' => [
        'class' => 'app\components\IndexerBehavior',
        // ...  Initialize property values
    ],
]

Use configuration

The configuration in Yii can be used in many scenarios. At the beginning of this chapter, we show how to use [[Yii:: createobject()]] to create objects according to configuration information. This section describes the two main uses of configuration - configuring applications and configuring widgets.

Application configuration

application The configuration of is probably one of the most complex. Because the [[yii\web\Application|application]] class has many configurable properties and events. More importantly, its [[yii\web\Application::components|components]] attribute can receive the configuration array and register it as a component through the application. The following is an example for Basic application template Application configuration summary:

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
        'log' => [
            'class' => 'yii\log\Dispatcher',
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                ],
            ],
        ],
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=stay2',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],
];

The reason why there is no class key in the configuration is that this configuration is applied in the following entry script, and the class name has been specified.

(new yii\web\Application($config))->run();

For more information about applying the components attribute configuration, please refer to application as well as Service Locator Chapter.

Since version 2.0.11, the system configuration supports using the container attribute Dependency injection container For example:

$config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php',
    'container' => [
        'definitions' => [
            'yii\widgets\LinkPager' => ['maxButtonCount' => 5]
        ],
        'singletons' => [
            // Dependency injection container singleton configuration
        ]
    ]
];

Please refer to Dependency injection container Below Advanced application examples Get more definitions and singletons configuration items and practical examples.

Widget configuration

use Widget When, you often need to configure it to customize its properties. Both the [[yii\base\Widget::widget()]] and [[yii\base\Widget::begin()]] methods can be used to create widgets. They can accept configuration arrays:

use yii\widgets\Menu;

echo Menu::widget([
    'activateItems' => false,
    'items' => [
        ['label' => 'Home', 'url' => ['site/index']],
        ['label' => 'Products', 'url' => ['product/index']],
        ['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
    ],
]);

The above code creates a widget Menu and initializes its activateItems property to false. The item property is also configured as the Menu item to be displayed.

Please note that the class name yii\widgets\Menu has been given in the code, and the configuration array should no longer contain the class key.

configuration file

When the content of configuration is very complex, the common practice is to store it in one or more PHP files, which are called configuration files. A configuration file returns a PHP array. For example, store the application configuration information like this in a file named web PHP file:

return [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require __DIR__ . '/../vendor/yiisoft/extensions.php',
    'components' => require __DIR__ . '/components.php',
];

Since the components configuration is also complex, the above code stores them in separate components PHP file and included in the web In PHP. components. The contents of PHP are as follows:

return [
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
    ],
    'log' => [
        'class' => 'yii\log\Dispatcher',
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
            ],
        ],
    ],
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=stay2',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
];

Only "require" is needed to obtain the configuration content of a configuration file, such as:

$config = require 'path/to/web.php';
(new yii\web\Application($config))->run();

Default configuration

The [[Yii::createObject()]] method is based on Dependency injection container realization. When you create an object with [[Yii:: createobject()]], you can attach a series of default configurations to any instance of the specified class. The default configuration can also be Entry script Call Yii:: $container->set () to define.

For example, if you want to customize the [[yii\widgets\LinkPager]] widget so that the pager can display up to 5 page turning buttons (the default is 10), you can use the following code:

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

If you don't use the default configuration, you have to configure the value of maxButtonCount wherever you use the pager.

Environment constant

The configuration often changes with the different environments in which the application runs. For example, in a development environment, you might use the name mydb_dev's database, while the production environment uses mydb_prod database. In order to facilitate switching the use environment, Yii provides a Yii defined in the entry script_ Env constant. As follows:

defined('YII_ENV') or define('YII_ENV', 'dev');

You can put YII_ENV is defined as any of the following values:

  • Production environment: prod. Constant YII_ENV_PROD will be considered true. If you haven't modified it, this is Yii_ The default value of env.
  • dev: development environment. Constant YII_ENV_DEV will be considered true.
  • Test: test environment. Constant YII_ENV_TEST will be treated as true.

With these environment constants, you can carry out differentiated configuration according to the current application running environment. For example, an application may contain the following code, which is only enabled in the development environment Debugging tools.

$config = [...];

if (YII_ENV_DEV) {
    // Configuration adjustment based on 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';
}

return $config;

💖 Those who like this document are welcome to like, collect, leave a message or forward it. Thank you for your support! Author email: zhuzixian520@126.com

This article was first published in LearnKu.com On the website.