Application properties
A Yii2 application can be configured through several properties.
The properties that need to be configured in any application are listed in the following table:
Properties |
Description |
---|---|
|
This indicates a unique ID to distinguish this application from others. It is mainly used programmatically. An example of this property is |
|
This specifies the root directory of the application. This path is the starting point for all the other types of application objects, such as models, controllers, and views. An example of this property is |
The other common properties are listed in the following table:
Properties |
Description |
---|---|
|
This indicates an alias name for path definitions. They are defined using a key/value array and they are very useful when we need to set a path as a constant that live in the whole application. We type an alias preceded by an |
|
This property allows you to configure an array of components to be run during the application bootstrap process. A common usage is to load the log or profile component, gii, or any other component. Be careful not to load too many components, otherwise the response performance of your pages may degrade. An example of this property is |
|
This property captures every request and it is used in the maintenance mode of the site. |
|
This property points out a list of application components that you can use in the whole application. |
|
This property specifies the language used to display the content. An example of this property is |
|
This property points out a list of application modules that can be used in the application. |
|
This property indicates the name of your app. An example of this property is |
|
This property specifies an array of parameters, through key/value pairs. This is a container for global params, such as the administrator's e-mail address. |
|
This property indicates the time zone that should be used in the application. An example of this property is |
|
This property points out the charset used in the application. The default value is |
|
This property contains a route to be used when a request does not a specify one. This property has different default values according to the environment we are using. For web applications, this value will be For console applications, this value will be |
Common application components
Here's a list of the most-used application components:
request
: This component handles all client requests and provides methods to easily get parameters from server global variables, such as$_SERVER
,$_POST
,$_GET
, and$_COOKIES
.The default state has
enableCookieValidation
set to true, so you need to setcookieValidationKey
parameter as shown in this example:'request' => [ 'cookieValidationKey' => 'hPpnJs7tvs0T4N2OGAY', ],
cache
: This component helps you handle cache data. Yii2 defaults to theFileCache
instance for the cache, but we can also configure anApcCache
,DbCache
,MemCache
, and so on.The following is a standard installation of Yii2:
'cache' => [ 'class' => 'yii\caching\FileCache', ],
user
: This component deals with user authentication in the app. The most important parameter is theidentityClass
parameter, which defines the class that contains the user's model data, in order to have a specific method to log in or log out a user from the app.Consider the following example:
'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ],
errorHandler
: This component provides functionalities to handle uncaught errors and exceptions. It can be configured by specifying the action to run.Consider the following example:
'errorHandler' => [ 'errorAction' => 'site/error', ],
mailer
: This component configures mailer connection parameters to the system that will send an e-mail. Usually, it is the same machine hosting our website, so the default values are probably correct.Consider the following example:
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ],
log
: This component is mainly used in the debug environment to log the app execution. We can set the debug level and destination.Consider the following example:
'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ],
db
: This component handles a database connection. We can have several db configuration in our app; in this case, we can define more components with theConnection
class located atyii\db\
.Consider the following example:
db => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'dbuser'', 'password' => 'dbpassword', 'charset' => 'utf8', ],
Handling application events
During its lifecycle, an application can trigger many events. These events can be declared in application configuration or programmatically. Common triggers are beforeRequest
, afterRequest
, beforeAction
, and afterAction
, but every object can have its own events.
For example, a common use of events is to set mysql db timezone
.
To set the time zone to UTC in db component configuration, we must define a handler for the afterOpen
event:
'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mydb', 'username' => 'dbuser', 'password' => 'dbpassword', 'charset' => 'utf8', 'on afterOpen' => function($event) { $event->sender->createCommand("SET time_zone = '+00:00'")->execute(); } ],
An anonymous function, attached to on afterOpen
event handlers, has an $event
parameter, which is an instance of the yii\base\ActionEvent
class. This class has a $sender
object that refers to the sender of the event. In this case, $sender
refers to the instance of database components (db). This property may also be null when this event is a class-level event.
The MVC pattern in Yii2
Yii2 is built according to the Model-View-Controller (MVC) design pattern.
Models, representing logic, are objects extended from \yii\base\Model
, which offer many features such as attribute, attribute labels, massive assignment (to fill object attributes directly for an array), validation rules, and data exporting.
Normally, in common apps, a Model will be generated from the database, extending yii\db\ActiveRecord
that implements the Active Record design pattern, with many methods to manipulate data. Yii2 provides Gii, a tool used to generate Model classes directly from the database's table structure.
Controllers, the bridge between view and model, are class instances extending from yii\base\Controller
, used to process requests and generate responses.
Controllers mainly contain functions whose name starts with the action prefix that allows the framework to recognize those functions as routes, which can be requested.
Finally, we will look at views that deal with displaying data to end users that are mainly rendered in the page layout from controllers.