concept-configurations.md 10 KB
Newer Older
1 2
Configurations
==============
3

4 5
Configurations are widely used in Yii for creating new objects or initializing existing objects.
They usually include the class names of the objects being created and a list of initial values
6 7 8
that should be assigned to object [properties](concept-properties.md). They may also include a list of
handlers that should be attached to the object [events](concept-events.md), and/or a list of
[behaviors](concept-behaviors.md) that should be attached to the objects.
Qiang Xue committed
9

10
In the following, a configuration is used to create and initialize a DB connection:
Qiang Xue committed
11 12

```php
13 14 15 16 17 18 19 20 21
$config = [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];

$db = Yii::createObject($config);
Qiang Xue committed
22 23
```

24 25 26
The [[Yii::createObject()]] method takes a configuration and creates an object based on the class name
specified in the configuration. When the object is being instantiated, the rest of the configuration
will be used to initialize the object properties, event handlers and/or behaviors.
Qiang Xue committed
27

28 29
If you already have an object, you may use [[Yii::configure()]] to initialize the object properties with
a configuration, like the following,
Qiang Xue committed
30 31

```php
32
Yii::configure($object, $config);
Qiang Xue committed
33 34
```

35
Note that in this case, the configuration should not contain the `class` element.
Qiang Xue committed
36

37

38
<a name="configuration-format"></a>
39 40
Configuration Format
--------------------
Larry Ullman committed
41

42
The format of a configuration can be formally described as follows,
Larry Ullman committed
43 44

```php
45 46 47 48 49 50
[
    'class' => 'ClassName',
    'propertyName' => 'propertyValue',
    'on eventName' => $eventHandler,
    'as behaviorName' => $behaviorConfig,
]
Larry Ullman committed
51 52
```

53
where
54

55 56
* The `class` element specifies a fully qualified class name for the object being created.
* The `propertyName` elements specify the property initial values. The keys are the property names, and the
57
  values are the corresponding initial values. Only public member variables and [properties](concept-properties.md)
58
  defined by getters/setters can be configured.
59
* The `on eventName` elements specify what handlers should be attached to the object [events](concept-events.md).
60
  Notice that the array keys are formed by prefixing event names with `on `. Please refer to
61
  the [Events](concept-events.md) section for supported event handler formats.
62
* And the `as behaviorName` elements specify what [behaviors](concept-behaviors.md) should be attached to the object.
63 64
  Notice that the array keys are formed by prefixing behavior names with `on `. `$behaviorConfig` represents
  the configuration for creating a behavior, like a normal configuration as we are describing here.
65

66
Below is an example showing a configuration with property initial values, event handlers and behaviors:
67 68

```php
69 70 71 72 73 74 75 76 77
[
    'class' => 'app\components\SearchEngine',
    'apiKey' => 'xxxxxxxx',
    'on search' => function ($event) {
        Yii::info("Keyword searched: " . $event->keyword);
    },
    'as indexer' => [
        'class' => 'app\components\IndexerBehavior',
        // ... property init values ...
78
    ],
79
]
80 81 82
```


83
<a name="using-configurations"></a>
84 85
Using Configurations
--------------------
86

87 88
Configurations are used in many places in Yii. At the beginning of this section, we have shown how to use
create an object according to a configuration by using [[Yii::createObject()]]. In this subsection, we will
89
describe application configurations and widget configurations - two major usages of configurations.
90

91

92
<a name="application-configurations"></a>
93 94 95 96 97 98 99
### Application Configurations

Configuration for an [application](structure-applications.md) is probably one of the most complex configurations.
This is because the [[yii\web\Application|application]] class has a lot of configurable properties and events.
More importantly, its [[yii\web\Application::components|components]] property can receive an array of configurations
for creating components that are registered through the application. The following is an abstract from the application
configuration file for the [basic application template](start-basic.md).
100 101

```php
102 103
$config = [
    'id' => 'basic',
104
    'basePath' => dirname(__DIR__),
105
    'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
106
    'components' => [
107 108 109 110 111 112
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'mail' => [
            'class' => 'yii\swiftmailer\Mailer',
        ],
113
        'log' => [
114
            'class' => 'yii\log\Dispatcher',
115 116 117 118 119 120 121
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                ],
            ],
        ],
122 123 124 125 126 127 128
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=stay2',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
129
    ],
Alexander Makarov committed
130
];
131 132
```

133 134
The configuration does not have a `class` key. This is because it is used as follows in
an [entry script](structure-entry-scripts.md), where the class name is already given,
Larry Ullman committed
135

136 137 138
```php
(new yii\web\Application($config))->run();
```
139

140
For more details about configuring the `components` property of an application can be found
141
in the [Applications](structure-applications.md) section and the [Service Locator](concept-service-locator.md) section.
142 143


144
<a name="widget-configurations"></a>
145
### Widget Configurations
146

147 148 149
When using [widgets](structure-widgets.md), you often need to use configurations to customize the widget properties.
Both of the [[yii\base\Widget::widget()]] and [[yii\base\Widget::beginWidget()]] methods can be used to create
a widget. They take a configuration array, like the following,
150 151

```php
152 153 154 155 156 157 158 159
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],
Qiang Xue committed
160 161
    ],
]);
162 163
```

164 165
The above code creates a `Menu` widget and initializes its `activeItems` property to be false.
The `items` property is also configured with menu items to be displayed.
Qiang Xue committed
166

167
Note that because the class name is already given, the configuration array should NOT have the `class` key.
Qiang Xue committed
168 169


170
<a name="configuration-files"></a>
171 172
Configuration Files
-------------------
Qiang Xue committed
173

174 175 176
When a configuration is very complex, a common practice is to store it in one or multiple PHP files, known as
*configuration files*. To use a configuration, simply "require" the corresponding configuration file.
For example, you may keep an application configuration in a file named `web.php`, like the following,
Qiang Xue committed
177 178 179

```php
return [
180 181 182 183
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
    'components' => require(__DIR__ . '/components.php'),
Qiang Xue committed
184 185
];
```
186

187 188
Because the `components` configuration is complex too, you store it in a separate file called `components.php`
and "require" this file in `web.php` as shown above. The content of `components.php` is as follows,
189 190 191

```php
return [
192 193 194 195 196 197 198 199 200 201 202 203
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
    'mail' => [
        'class' => 'yii\swiftmailer\Mailer',
    ],
    'log' => [
        'class' => 'yii\log\Dispatcher',
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
204 205 206
            ],
        ],
    ],
207 208 209 210 211 212 213
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=stay2',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
214 215 216
];
```

217 218 219 220 221 222 223 224
And the code for starting an application becomes,

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


225
<a name="default-configurations"></a>
226 227 228
Default Configurations
----------------------

229
The [[Yii::createObject()]] method is implemented based on a [dependency injection container](concept-di-container.md).
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
It allows you specify a set of the so-called *default configurations* which will be applied to ANY instances of
the specified classes when they are being created using [[Yii::createObject()]]. The default configurations
can be specified by calling `Yii::$container->set()` in the [bootstrapping](runtime-bootstrapping.md) code.

For example, if you want to customize [[yii\widgets\LinkPager]] so that ALL link pagers will show at most 5 page buttons
(the default value is 10), you may use the following code to achieve this goal,

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

Without using default configurations, you would have to configure `maxButtonCount` in every place where you use
link pagers.
245 246


247
<a name="environment-constants"></a>
248 249 250 251 252 253
Environment Constants
---------------------

Configurations often vary according to the environment in which an application runs. For example,
in development environment, you may want to use a database named `mydb_dev`, while on production server
you may want to use the `mydb_prod` database. To facilitate switching environments, Yii provides a constant
Qiang Xue committed
254
named `YII_ENV` that you may define in the [entry script](structure-entry-scripts.md) of your application.
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
For example,

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

You may define `YII_ENV` as one of the following values:

- `prod`: production environment. The constant `YII_ENV_PROD` will evaluate as true.
  This is the default value of `YII_ENV` if you do not define it.
- `dev`: development environment. The constant `YII_ENV_DEV` will evaluate as true.
- `test`: testing environment. The constant `YII_ENV_TEST` will evaluate as true.

With these environment constants, you may specify your configurations conditionally based on
the current environment. For example, your application configuration may contain the following
code to enable the [debug toolbar and debugger](tool-debugger.md) in development environment.

```php
$config = [...];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';
}

return $config;
```