官术网_书友最值得收藏!

  • Yii2 By Example
  • Fabrizio Caldarelli
  • 734字
  • 2021-07-16 19:38:54

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:

The other common properties are listed in the following table:

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 set cookieValidationKey parameter as shown in this example:

    'request' => [
    'cookieValidationKey' => 'hPpnJs7tvs0T4N2OGAY',
    ],
  • cache: This component helps you handle cache data. Yii2 defaults to the FileCache instance for the cache, but we can also configure an ApcCache, 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 the identityClass 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 the Connection class located at yii\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.

主站蜘蛛池模板: 宁国市| 兴国县| 大关县| 融水| 湛江市| 紫云| 兴国县| 安庆市| 铁岭市| 莲花县| 江门市| 寿光市| 富平县| 芒康县| 望江县| 蛟河市| 伊金霍洛旗| 延津县| 衡山县| 炎陵县| 建瓯市| 新密市| 铁力市| 桃江县| 安仁县| 临漳县| 博白县| 临猗县| 互助| 楚雄市| 加查县| 辉南县| 通渭县| 福建省| 电白县| 搜索| 五莲县| 上饶县| 龙山县| 天门市| 观塘区|