Yii applications rely upon components to perform most of the common tasks, such as connecting to a database, routing browser
requests, and handling sessions. How these stock components behave can be adjusted by *configuring* your Yii application.
The majority of components have sensible defaults, so it's unlikely that you'll spend a lot of time configuring
them. Still there are some mandatory settings, such as the database connection, that you will have to establish.
The majority of components have sensible default settings, so it's unlikely that you'll do a lot of configuration. Still, there are some mandatory configuration settings that you will have to establish, such as the database connection.
How an application is configured depends on application template but there are some general principles applying in any case.
How an application is configured depends upon the application template in use, but there are some general principles that apply in every Yii case.
Configuring options in bootstrap file
-------------------------------------
Configuring options in the bootstrap file
-----------------------------------------
For each application in Yii there is at least one bootstrap file. For web applications it's typically `index.php`, for
console applications it's `yii`. Both are doing nearly the same job:
For each application in Yii there is at least one bootstrap file: a PHP script through which all requests are handled. For web applications, the bootstrap file is typically `index.php`; for
console applications, the bootstrap file is `yii`. Both bootstrap files perform nearly the same job:
1. Setting common constants.
2. Including Yii itself.
2. Including the Yii framework itself.
3. Including [Composer autoloader](http://getcomposer.org/doc/01-basic-usage.md#autoloading).
4. Reading config file into `$config`.
5. Creating new application instance using `$config` and running it.
4. Reading the configuration file into `$config`.
5. Creating a new application instance, configured via `$config`, and running that instance.
The Bootstrap file is not the part of framework but your application so it's OK to adjust it to fit your application. Typical
adjustments are the value of `YII_DEBUG` that should never be `true` on production and the way config is read:
Like any resource in your Yii application, the bootstrap file can be edited to fit your needs. A typical change is to the value of `YII_DEBUG`. This constant should be `true` during development, but always `false` on production sites.
The default bootstrap structure sets `YII_DEBUG` to `false` if not defined:
```php
defined('YII_DEBUG')ordefine('YII_DEBUG',false);
```
During development, you can change this to `true`:
```php
define('YII_DEBUG',true);// Development only
defined('YII_DEBUG')ordefine('YII_DEBUG',false);
```
Configuring application instance
--------------------------------
Configuring the application instance
------------------------------------
It was mentioned above that application is configured in bootstrap file when its instance is created. Config is typically
stored in a PHP file in the `/config` directory of the application and looks like the following:
An application instance is configured when it's created in the bootstrap file. The configuration is typically
stored in a PHP file stored in the `/config` application directory. The file has this structure to begin:
```php
<?php
...
...
@@ -45,18 +52,18 @@ return [
];
```
In the above array keys are names of application properties. Depending on application type you can check properties of
either [[yii\web\Application]] or [[yii\console\Application]]. Both are extended from[[yii\base\Application]].
The configuration is a large array of key-value pairs. In the above, the array keys are the names of application properties. Depending upon the application type, you can configure the properties of
either [[yii\web\Application]] or [[yii\console\Application]] classes. Both classes extend [[yii\base\Application]].
> Note that you can configure not only public class properties but anything accessible via setter. For example, to
configure runtime path you can use key named `runtimePath`. There's no such property in the application class but
since there's a corresponding setter named `setRuntimePath` it will be properly configured.
This feature is added to any class that extends from [[yii\base\Object]] which is nearly any class of the Yii framework.
Note that you can configure not only public class properties, but any property accessible via a setter. For example, to
configure the runtime path, you can use a key named `runtimePath`. There's no such property in the application class, but
since the class has a corresponding setter named `setRuntimePath`, `runtimePath` becomes configurable.
The ability to configure properties via setters is available to any class that extends from [[yii\base\Object]], which is nearly every class in the Yii framework.
Configuring application components
----------------------------------
Majority of Yii functionality are application components. These are attached to application via its `components` property:
The majority of the Yii functionality comes from application components. These components are attached to the application instance via the instance's `components` property:
```php
<?php
...
...
@@ -81,23 +88,21 @@ return [
];
```
In the above four components are configured: `cache`, `user`, `errorHandler`, `log`. Each entry key is a component ID
and the value is the configuration array. ID is used to access the component like `\Yii::$app->myComponent`.
Configuration array has one special key named `class` that sets the component class. The rest of the keys and values are used
to configure component properties in the same way as top-level keys are used to configure application properties.
In the above code, four components are configured: `cache`, `user`, `errorHandler`, `log`. Each entry's key is a component ID. The values are subarrays used to configure that component. The component ID is also used to access the component anywhere within the application, using code like `\Yii::$app->myComponent`.
The configuration array has one special key named `class` that identifies the component's base class. The rest of the keys and values are used
to configure component properties in the same way as top-level keys are used to configure the application's properties.
Each application has a predefined set of components. In case of configuring one of these, the `class` key is omitted and
application default class is used instead. You can check `registerCoreComponents()` method of the application you are using
Each application has a predefined set of components. To configure one of these, the `class` key can be omitted to use the default Yii class for that component. You can check the `registerCoreComponents()` method of the application you are using
to get a list of component IDs and corresponding classes.
Note that Yii is smart enough to configure the component when it's actually used i.e. if `cache` is never used it will
not be instantiated and configured at all.
Note that Yii is smart enough to only configure the component when it's actually being used: for example, if you configure the `cache` component in your configuration file but never use the `cache` component in your code, no instance of that component will be created and no time is wasted configuring it.
Setting component defaults classwide
------------------------------------
For each component you can specifiy classwide defaults. For example, if we want to change class for all `LinkPager`
widgets without specifying it over and over again when widget is called we can do it like the following:
For each component you can specifiy classwide defaults. For example, if you want to change the class used for all `LinkPager`
widgets without specifying the class for every widget usage, you can do the following:
```php
\Yii::$objectConfig=[
...
...
@@ -109,5 +114,5 @@ widgets without specifying it over and over again when widget is called we can d
];
```
The code above should be executed once before `LinkPager` widget is used. It can be done in `index.php`, application
config or anywhere else.
\ No newline at end of file
The code above should be executed once before `LinkPager` widget is used. It can be done in `index.php`, the application
Error handling in Yii is different from plain PHP. First of all, all non-fatal errors are converted to exceptions so
you can use `try`-`catch` to work with these. Second, even fatal errors are rendered in a nice way. In debug mode that
means you have a trace and a piece of code where it happened so it takes less time to analyze and fix it.
Error handling in Yii is different than handling errors in plain PHP. First of all, Yii will convert all non-fatal errors to *exceptions*. By doing so, you can gracefully handle them using `try`-`catch`. Second, even fatal errors in Yii are rendered in a nice way. This means that in debugging mode, you can trace the causes of fatal errors in order to more quickly identify the cause of the problem.
Using controller action to render errors
----------------------------------------
Rendering errors in a dedicated controller action
-------------------------------------------------
Default Yii error page is great for development mode and is OK for production if `YII_DEBUG` is turned off but you may
have an idea how to make it more suitable for your project. An easiest way to customize it is to use controller action
for error rendering. In order to do so you need to configure `errorHandler` component via application config:
The default Yii error page is great when developing a site, and is acceptable for production sites if `YII_DEBUG` is turned off in your bootstrap index.php file. But but you may want to customize the default error page to make it more suitable for your project.
The easiest way to create a custom error page it is to use a dedicated controller action for error rendering. First, you'll need to configure the `errorHandler` component in the application's configuration:
```php
return[
...
...
@@ -22,7 +20,7 @@ return [
],
```
After it is done in case of error, Yii will launch `SiteController::actionError()`:
With that configuration in place, whenever an error occurs, Yii will execute the "error" action of the "Site" controller. That action should look for an exception and, if present, render the proper view file, passing along the exception:
```php
publicfunctionactionError()
...
...
@@ -33,8 +31,22 @@ public function actionError()
}
```
Since most of the time you need to adjust look and feel only, Yii provides `ErrorAction` class that can be used in
controller instead of implementing action yourself:
Next, you would create the `views/site/error.php` file, which would make use of the exception. The exception object has the following properties:
*`code`: the HTTP status code (e.g. 403, 500)
*`type`: the error type (e.g. CHttpException, PHP Error)
*`message`: the error message
*`file`: the name of the PHP script file where the error occurs
*`line`: the line number of the code where the error occurs
*`trace`: the call stack of the error
*`source`: the context source code where the error occurs
[[Need to confirm the above for Yii 2.]]
Rendering errors without a dedicated controller action
Instead of creating a dedicated action within the Site controller, you could just indicate to Yii what class should be used to handle errors:
```php
publicfunctionactions()
...
...
@@ -47,10 +59,10 @@ public function actions()
}
```
After defining `actions` in `SiteController` as shown above you can create `views/site/error.php`. In the view there
are three variables available:
After associating the class with the error as in the above, define the `views/site/error.php` file, which will automatically be used. The view will be passed three variables:
-`$name`: the error name
-`$message`: the error message
-`$exception`: the exception being handled
The `$exception` object will have the same properties outlined above.
By default Yii uses PHP as template language, but you can configure it to support other rendering engines, such as
By default, Yii uses PHP as its template language, but you can configure Yii to support other rendering engines, such as
[Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/).
The `view` component is responsible for rendering views. You can add a custom template engines by reconfiguring this
The `view` component is responsible for rendering views. You can add a custom template engine by reconfiguring this
component's behavior:
```php
...
...
@@ -30,22 +30,21 @@ component's behavior:
]
```
In the config above we're using Smarty and Twig. In order to get these extensions in your project you need to modify
your `composer.json`to include
In the code above, both Smarty and Twig are configured to be useable by the view files. But in order to get these extensions into your project, you need to also modify
your `composer.json`file to include them, too:
```
"yiisoft/yii2-smarty": "*",
"yiisoft/yii2-twig": "*",
```
in `require` section and then run `composer update --preder-dist`.
That code would be added to the `require` section of `composer.json`. After making that change and saving the file, you can install the extensions by running `composer update --preder-dist` in the command-line.
Twig
----
To use Twig, you need to create templates in files with the `.twig` extension (or use another file extension but configure the component accordingly).
Unlike standard view files, when using Twig, you must include the extension when calling`$this->render()`
or `$this->renderPartial()`from your controller:
To use Twig, you need to create templates in files that have the `.twig` extension (or use another file extension but configure the component accordingly).
Unlike standard view files, when using Twig you must include the extension in your`$this->render()`
Additional filters may be added via config's `filters` option:
Additional filters may be added via the application configuration's `filters` option:
```php
'filters'=>[
...
...
@@ -96,7 +95,7 @@ Additional filters may be added via config's `filters` option:
],
```
Then in the template you can use
Then in the template you can use:
```
{{ model|jsonEncode }}
...
...
@@ -106,8 +105,8 @@ Then in the template you can use
Smarty
------
To use Smarty, you need to create templates in files with the `.tpl` extension (or use another file extension but configure the component accordingly). Unlike standard view files, when using Smarty, you must include the extension when calling`$this->render()`
or `$this->renderPartial()`from your controller:
To use Smarty, you need to create templates in files that have the `.tpl` extension (or use another file extension but configure the component accordingly). Unlike standard view files, when using Smarty you must include the extension in your`$this->render()`
- Bug #1265: AssetController does not override 'js' and 'css' for compressed bundles (klimov-paul)
- Bug #1326: The `visible` setting for `DetailView` doesn't work as expected (qiangxue)
- Bug #1412: `FileValidator` and `ImageValidator` still trigger `uploadRequired` error in some case when `skipOnEmpty` is true and no upload is provided (qiangxue)
...
...
@@ -41,6 +40,7 @@ Yii Framework 2 Change Log
- Bug #2084: AssetController adjusting CSS URLs declared at same line fixed (klimov-paul)
- Bug #2091: `QueryBuilder::buildInCondition()` fails to handle array not starting with index 0 (qiangxue)
- Bug #2160: SphinxQL does not support OFFSET (qiangxue, romeo7)
- Bug #2209: When I18N message translation is missing source language is now used for formatting (samdark)
- Bug #2212: `yii\gridview\DataColumn` generates incorrect labels when used with nosql DB and there is no data (qiangxue)
- Bug #2298: Fixed the bug that Gii controller generator did not allow digit in the controller ID (qiangxue)
- Bug #2303: Fixed the bug that `yii\base\Theme::pathMap` did not support dynamic update with path aliases (qiangxue)
- Enh #1579: throw exception when the given AR relation name does not match in a case sensitive manner (qiangxue)
- Enh #1581: Added `ActiveQuery::joinWith()` and `ActiveQuery::innerJoinWith()` to support joining with relations (qiangxue)
...
...
@@ -92,6 +91,7 @@ Yii Framework 2 Change Log
- Enh #2008: `yii message/extract` is now able to save translation strings to database (kate-kate, samdark)
- Enh #2043: Added support for custom request body parsers (danschmidt5189, cebe)
- Enh #2051: Do not save null data into database when using RBAC (qiangxue)
- Enh #2054: Added support for using custom application configuration with the console command runner (qiangxue)
- Enh #2079:
- i18n now falls back to `en` from `en-US` if message translation isn't found (samdark)
- View now falls back to `en` from `en-US` if file not found (samdark)
...
...
@@ -124,6 +124,7 @@ Yii Framework 2 Change Log
- Enh:#2211: Added typecast database types into php types (dizews)
- Enh #2240: Improved `yii\web\AssetManager::publish()`, `yii\web\AssetManager::getPublishedPath()` and `yii\web\AssetManager::getPublishedUrl()` to support aliases (vova07)
- Enh #2325: Adding support for the `X-HTTP-Method-Override` header in `yii\web\Request::getMethod()` (pawzar)
- Enh #2364: Take into account current error reporting level in error handler (gureedo)
- Chg #1519: `yii\web\User::loginRequired()` now returns the `Response` object instead of exiting the application (qiangxue)
- Chg #1586: `QueryBuilder::buildLikeCondition()` will now escape special characters and use percentage characters by default (qiangxue)
- Chg #1610: `Html::activeCheckboxList()` and `Html::activeRadioList()` will submit an empty string if no checkbox/radio is selected (qiangxue)
...
...
@@ -164,6 +165,7 @@ Yii Framework 2 Change Log
- Chg: Removed implementation of `Arrayable` from `yii\Object` (qiangxue)
- Chg: Renamed `ActiveRecordInterface::createActiveRelation()` to `createRelation()` (qiangxue)
- Chg: The scripts in asset bundles are now registered in `View` at the end of `endBody()`. It was done in `endPage()` previously (qiangxue)
- Chg: Renamed `csrf-var` to `csrf-param` for CSRF header name (Dilip)