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

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

Larry Ullman committed
9
In the following, a configuration is used to create and initialize a database connection:
Qiang Xue committed
10 11

```php
12 13 14 15 16 17 18 19 20
$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
21 22
```

Larry Ullman committed
23 24
The [[Yii::createObject()]] method takes a configuration array as its argument, and creates an object by instantiating the class named in the configuration. When the object is instantiated, the rest of the configuration
will be used to initialize the object's properties, event handlers, and behaviors.
Qiang Xue committed
25

Larry Ullman committed
26 27
If you already have an object, you may use [[Yii::configure()]] to initialize the object's properties with
a configuration array:
Qiang Xue committed
28 29

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

Larry Ullman committed
33
Note that, in this case, the configuration array should not contain a `class` element.
Qiang Xue committed
34

35

Qiang Xue committed
36
## Configuration Format <a name="configuration-format"></a>
Larry Ullman committed
37

Larry Ullman committed
38
The format of a configuration can be formally described as:
Larry Ullman committed
39 40

```php
41 42 43 44 45 46
[
    'class' => 'ClassName',
    'propertyName' => 'propertyValue',
    'on eventName' => $eventHandler,
    'as behaviorName' => $behaviorConfig,
]
Larry Ullman committed
47 48
```

49
where
50

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

Larry Ullman committed
62
Below is an example showing a configuration with initial property values, event handlers, and behaviors:
63 64

```php
65 66 67 68 69 70 71 72 73
[
    '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 ...
74
    ],
75
]
76 77 78
```


Qiang Xue committed
79
## Using Configurations <a name="using-configurations"></a>
80

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

85

Qiang Xue committed
86
### Application Configurations <a name="application-configurations"></a>
87 88 89 90 91 92

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).
93 94

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

126 127
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
128

129 130 131
```php
(new yii\web\Application($config))->run();
```
132

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


Qiang Xue committed
137
### Widget Configurations <a name="widget-configurations"></a>
138

139 140 141
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,
142 143

```php
144 145 146 147 148 149 150 151
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
152 153
    ],
]);
154 155
```

156 157
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
158

159
Note that because the class name is already given, the configuration array should NOT have the `class` key.
Qiang Xue committed
160 161


Qiang Xue committed
162
## Configuration Files <a name="configuration-files"></a>
Qiang Xue committed
163

164
When a configuration is very complex, a common practice is to store it in one or multiple PHP files, known as
Qiang Xue committed
165
*configuration files*. A configuration file returns a PHP array representing the configuration.
166
For example, you may keep an application configuration in a file named `web.php`, like the following,
Qiang Xue committed
167 168 169

```php
return [
170 171 172 173
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
    'components' => require(__DIR__ . '/components.php'),
Qiang Xue committed
174 175
];
```
176

177 178
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,
179 180 181

```php
return [
182 183 184
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
185
    'mailer' => [
186 187 188 189 190 191 192 193
        'class' => 'yii\swiftmailer\Mailer',
    ],
    'log' => [
        'class' => 'yii\log\Dispatcher',
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
194 195 196
            ],
        ],
    ],
197 198 199 200 201 202 203
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=stay2',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ],
204 205 206
];
```

Qiang Xue committed
207
To get a configuration stored in a configuration file, simply "require" it, like the following:
208 209 210 211 212 213 214

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


Qiang Xue committed
215
## Default Configurations <a name="default-configurations"></a>
216

217
The [[Yii::createObject()]] method is implemented based on a [dependency injection container](concept-di-container.md).
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
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.
233 234


Qiang Xue committed
235
## Environment Constants <a name="environment-constants"></a>
236 237 238 239

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
240
named `YII_ENV` that you may define in the [entry script](structure-entry-scripts.md) of your application.
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
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;
```