Configuration | Core Architecture | Yii Chinese Document 2.0.x

Configurations

Configuration is widely used in Yii when creating new objects and initializing existing ones. Configurations usually contain the class name of the object being created and a set of objects to be assigned to attribute Initial value. It may also contain a set of objects that will be attached to Event Handle on. And a set of which will be attached to the object 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);

[[Yii::createObject()]] Method accepts a configuration array and creates an object based on 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 initialize their properties based on configuration using the [[Yii::configure()]] method, just like this:

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

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

Configuration Format

A configuration's format 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 for that property. Only public member variables and those defined by getter/setter attribute Can be configured.
  • The on eventName element specifies the attachment to the object Event What is the handle on the. Notice that the key name of the array consists of on prefix plus event name. Please refer to Event Chapter Understanding Event Handle Format.
  • The as behaviorName element specifies the 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 for the creation behavior in the same format as described earlier.

Below is an example of configuring initialization property values, event handles, and behavior:

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

Use Configuration

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

Application Configuration

application Configuration is probably one of the most complex configurations. Because the [[yii\web\Application|application]] class has many configurable properties and events. More importantly, its [[yii\web\Application::components|components]] property accepts the configuration array and registers it as a component through the application. Here is a list of 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 there is no class key in the configuration is that the configuration is applied in the entry script below and the class name is already specified.

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

More information about applying components property configurations can be found application as well as Service Locator Chapter.

Since version 2.0.11, system configuration supports the use of container properties to configure Dependent 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' => [
            // Dependent Injection Container Singleton Configuration
        ]
    ]
];

Please refer to Dependent Injection Container Below Advanced Application Instances Get more examples of definitions and singletons configurations and actual use.

Widget Configuration

Use Widgets Often, you need to configure it to customize its properties. [[yii\base\Widget::widget()]] and [[yii\base\Widget::begin()]] methods can both 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 code above creates a widget Menu and initializes its activateItems property to false. The item property is also configured as a menu entry to be displayed.

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

configuration file

When the content of a configuration is complex, it is common practice 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 under the name web like this. PHP file:

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

Given the complexity of the components configuration, 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',
    ],
];

Just "require" is required to get the configuration contents of a configuration file, like this:

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

Default Configuration

[[Yii::createObject()]] Method is based on Dependent Injection Container Realization. When you create an object with [[Yii::creatObject()]]], you can attach a series of default configurations to any instance of the specified class. The default configuration can also be found in 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 five paging buttons (default is 10), you can do this with the following code:

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

Without the default configuration, you have to configure the value of maxButtonCount wherever you use the pager.

Environmental Constants

Configuration often changes depending on the environment 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. To facilitate switching environments, Yii provides a YII_defined in the entry script ENV constant. The following:

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

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

  • prod: production environment. Constant YII_ENV_PROD will be considered true. If you haven't modified it, this is YII_ Default value of ENV.
  • dev: Development environment. Constant YII_ENV_DEV will be considered true.
  • test: test environment. Constant YII_ENV_TEST will be considered true.

With these environment constants, you can configure differently depending on the running environment of your current application. For example, an application can contain the following code that is only open in a development environment Debugging Tools.

$config = [...];

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

return $config;

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

This article begins with LearnKu.com On the website.

Added by NickG21 on Fri, 04 Feb 2022 19:51:29 +0200