Detailed explanation of operation examples of Yii framework applications

Time:2020-10-17

This paper describes the operation of Yii framework applications. For your reference, the details are as follows:

Application subject

Application agent is the object that manages the whole structure and life cycle of Yii application system. Each Yii application system can only contain one application principal, which can be created in the entry script and can be passed through the expression\Yii::$appGlobal access.

Information:When we say “an application”, it may be an application subject object or an application system, which is determined by the context.

Yii has two kinds of application subjects: Web application subject and console application subject. As the name shows, the former mainly deals with web page requests, and the latter handles console requests.

Application principal configuration

As shown below, when the entry script creates an application principal, it loads a configuration file and passes it to the application principal.

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
 
//Load application principal configuration
$config = require __DIR__ . '/../config/web.php';
 
//Instantiate and configure application subjects
(new yii\web\Application($config))->run();

Similar to other configuration files, the application body configuration file indicates how to set the initial properties of the application object. Due to the complexity of the application body configuration, it is generally saved in multiple, similar to the above web.php In the configuration file.

Application principal attribute 〈

There are many important properties to be configured in the application principal configuration file, which specify the running environment of the application principal. For example, the application body needs to know how to load the controller, where to save the temporary files, and so on. Let’s briefly describe these properties below.

Essential attributes

In an application, at least two properties should be configured: ID and basepath.

id

The ID attribute is used to distinguish the unique ID of other applications. Mainly for program use. In order to facilitate collaboration, it is better to use a number as the application principal ID, but it is not required to be a number.

basePath

Basepath specifies the root directory of the app. The root directory contains all the protected source code of the application system. In the root directory, you can see themodels, views, controllersAnd so on.

You can use a path or a path alias to configure the basepath property in. The directory corresponding to both formats must exist, otherwise an exception will be thrown. The system will userealpath()Function normalization configuration path

The basepath property is often used to derive some other important paths, such as the runtime path, so the system is predefined@appRepresents this path. The derived path can be composed of this alias (e.g@app/runtimeRepresents the path of the runtime).

Important attributes

The properties described in this section usually need to be set because different application properties are different.

aliases

This property allows you to define multiple aliases with an array. The key of the array is the alias name, and the value is the corresponding path. For example:


[
 'aliases' => [
  '@name1' => 'path/to/path1',
  '@name2' => 'path/to/path2',
 ],
]

Use this property to define the alias instead of the Yii:: setalias() method.

bootstrap

This property is very useful. It allows you to specify the components that the bootstrapping process needs to run in the boot phase with an array. For example, if you want a module to customize URL rules, you can add the module ID to the bootstrap array.

Each component in the property needs to specify one of the following:

  • Application component ID
  • Module ID
  • Class name
  • Configuration array
  • Creates and returns a nameless function of a component

For example:

[
 'bootstrap' => [
  //Application component ID or module ID
  'demo',
 
  //Class name
  'app\components\Profiler',
 
  //Configuration array
  [
   'class' => 'app\components\Profiler',
   'level' => 3,
  ],
 
  //Anonymous function
  function () {
   return new app\components\Profiler();
  }
 ],
]

Information:If the module ID and the application component id have the same name, the application component ID is preferred. If you want to use the module ID, you can use the following unnamed function to return the module ID.


[
 function () {
  return Yii::$app->getModule('user');
 },
]

During the startup phase, each component is instantiated. If the component class implements the interface Yii / base / bootstrap interface, the bootstrap() method is also called.

For example, in the configuration of basic application template application body, it will run in the startup phase under the development environmentdebugandgiimodular.


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

be careful:Starting too many components can degrade system performance, because each request requires the startup component to be rerun, so configure the startup component carefully.

catchAll

This property is only supported by Web Applications Web applications. It specifies a controller method to handle all user requests, usually used in maintenance mode, and the same method handles all user requests.

The configuration is an array. The first item specifies the route of the action, and the remaining array items (key value pairs) specify the parameters to be passed to the action, for example:


[
 'catchAll' => [
  'offline/notice',
  'param1' => 'value1',
  'param2' => 'value2',
 ],
]

Information:When this property is turned on, the debugging panel in the development environment will not work.

components

This is the most important property that allows you to register multiple application components that are used elsewhere. For example


[
 'components' => [
  'cache' => [
   'class' => 'yii\caching\FileCache',
  ],
  'user' => [
   'identityClass' => 'app\models\User',
   'enableAutoLogin' => true,
  ],
 ],
]

Each application component specifies an array of key value pairs. Key represents component ID and value represents component class name or configuration.

In the application, you can register any component, and you can use the expression\Yii::$app->ComponentIDGlobal access.

controllerMap

This property allows you to specify a controller ID to any controller class. Yii follows a default rule to specify the controller ID to any controller class (e.gpostcorrespondingapp\controllers\PostController)。 This default rule can be broken by configuring this property. In the following example,accountCorresponding toapp\controllers\UserControllerarticleCorresponding toapp\controllers\PostController


[
 'controllerMap' => [
  'account' => 'app\controllers\UserController',
  'article' => [
   'class' => 'app\controllers\PostController',
   'enableCsrfValidation' => false,
  ],
 ],
]

The key of the array represents the controller ID, and the value of the array represents the corresponding class name.

controllerNamespace

This property specifies the default namespace of the controller class, which isapp\controllers。 For example, the controller ID ispostDefault correspondencePostController(without a namespace), the full name of the class isapp\controllers\PostController

The controller class file may be placed in a subdirectory of the directory corresponding to this namespace, for example, controller IDadmin/postThe full name of the corresponding controller class isapp\controllers\admin\PostController

It is very important that the controller class can be automatically loaded. The actual namespace of the controller class corresponds to this property. Otherwise, you will receive “page not found” when accessing.

If you want to break the above rules, you can configure the controllermap property.

language

This property specifies the language the application is presented to the end user. The default isenLogo in English. Other languages can configure this property if necessary.

This attribute affects all kinds of internationalization, including information translation, date format, number format, etc. For example, the Yii / ju / datepicker widget displays the calendar and date format for the corresponding language based on this property.

It is recommended to follow IETF language tag to set the language, such asenFor English,en-USFor English (USA)

modules

This property specifies the module that the application contains.

This attribute uses an array to contain multiple module classes. The key of the array is the module ID. for example:

[
 'modules' => [
  //"Booking" module and corresponding classes
  'booking' => 'app\modules\booking\BookingModule',
 
  //"Comment" module and corresponding configuration array
  'comment' => [
   'class' => 'app\modules\comment\CommentModule',
   'db' => 'db',
  ],
 ],
]

name

This attribute specifies the name of the application that you may want to present to the end user. Unlike the ID attribute that requires uniqueness, this attribute may not be unique. This attribute is used to display the purpose of the application.

If the code in other places is not used, you can not configure this property.

params

This attribute is an array, which specifies parameters that can be accessed globally instead of hard coded numbers and characters in the program. It is a good habit to define the parameters in application to a separate file and access them at any time. For example, define the length and width of the thumbnail with parameters as follows:


[
 'params' => [
  'thumbnail.size' => [128, 128],
 ],
]

Then simply use the following code to get the length and width parameters you need:


$size = \Yii::$app->params['thumbnail.size'];
$width = \Yii::$app->params['thumbnail.size'][0];

If you want to modify the length and width of the thumbnail in the future, you only need to modify this parameter without the relevant code.

sourceLanguage

This property specifies the language of the application code. The default is'en-US'Identify English (USA). If the application is not in English, please modify this property.

Similar to the language attribute, configuring this property follows IETF language tag. For exampleenFor English,en-USFor English (USA)

timeZone

This property provides a way to modify the default time zone in the PHP running environment. To configure this property is essentially to call the PHP function date_ default_ timezone_ Set(), for example:


[
 'timeZone' => 'America/Los_Angeles',
]

version

This property specifies the version of the application. The default is'1.0'If other code is not used, it can not be configured.

Utility properties

The properties described in this section are set infrequently and usually use system default values. If you want to change the default values, you can configure these properties.

charset

This property specifies the character set used by the application. The default value is'UTF-8', most of the applications are using it, unless the existing system uses a lot of non Unicode data, you need to change this property.

defaultRoute

This attribute specifies the response routing rule for unconfigured requests, which may contain module ID, controller ID, and action ID. for examplehelp, post/create, admin/post/createIf the action ID is not specified, the default value specified in Yii / base / controller:: $defaultaction is used.

For Web Applications Web applications, the default value is'site'correspondingSiteControllerController and use the default action. Your access will not be displayed by defaultapp\controllers\SiteController::actionIndex()The results.

For console applications, the default value is'help'Corresponding to Yii / console / Controllers / helpcontroller:: actionindex(). Therefore, if you execute a command without parameters, help information is displayed by default.

extensions

This attribute uses the array list to specify the extension to be installed and used by the application. It is used by default@vendor/yiisoft/extensions.phpThe array returned by the file. When you use composer to install extensions,extensions.phpWill be automatically generated and maintained. So in most cases, you don’t need to configure this property.

In special cases, if you want to maintain the extension manually, you can refer to the following configuration:

[
 'extensions' => [
  [
   'name' => 'extension name',
   'version' => 'version number',
   'bootstrap' = >'bootstrap classname ', // optional, configurable array
   'alias' = > [// optional
    '@alias1' => 'to/path1',
    '@alias2' => 'to/path2',
   ],
  ],
 
  //... more like the extension above
 
 ],
]

As shown above, this property contains an array of extension definitions, each of which is annameandversionAn array of items. If the extension is to run during the boot start phase, it needs to be configuredbootstrapAnd the corresponding bootstrap class name or configuration array. Extensions can also define aliases

layout

This property specifies the name of the layout to be used by default for rendered views. The default value is'main'Under the corresponding layout pathmain.phpFile, if both the layout path and view path are the default values, the default layout file can use the path alias@app/views/layouts/main.php

If you do not want to set the default layout file, you can set this property tofalseThis is rare.

layoutPath

This property specifies the path to find the layout file. The default value islayoutsSubdirectories. If the view path uses the default value, the default layout path alias is@app/views/layouts

This property needs to be configured as a directory or path alias.

runtimePath

This attribute specifies the save path of temporary files such as log files and cache files. The default value is aliased@app/runtime

You can configure this attribute as a directory or path alias. Note that the application runtime has write permission to the path, and the end user cannot access the path, because the temporary file may contain some sensitive information.

To simplify access to the path, Yii predefines aliases@runtimeRepresents the path.

viewPath

This path specifies the root directory of the view file. The default value is aliased@app/viewsCan be configured as a directory or path alias

vendorPath

This attribute specifies the vendor path managed by composer, which contains all third-party libraries used by the application, including the Yii framework. The default value is aliased@app/vendor

It can be configured as a directory or path alias. When you modify it, be sure to modify the corresponding composer configuration.

To simplify access to the path, Yii predefines aliases@vendorRepresents the path.

enableCoreCommands

This attribute is only supported by console applications console applications. It is used to specify whether to enable the core commands in Yii. The default value istrue

Application events

The application will trigger the event during processing the request. You can configure the event handling code in the configuration file, as shown below:


[
 'on beforeRequest' => function ($event) {
  // ...
 },
]

on eventNameThe usage of the syntax is described in details in the configurations section

In addition, after the application body is instantiated, you can attach event handling code in the boot startup phase, such as:


\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) {
 // ...
});

EVENT_BEFORE_REQUEST

This event handles the request in the applicationbeforePreviously, the actual event was namedbeforeRequest

Before the event is triggered, the application body has been instantiated and configured, so it is very good to embed your code into the request processing process through the event mechanism. For example, in event processing, the language properties of Yii / base / application:: $language are set dynamically according to some parameters.

EVENT_AFTER_REQUEST

This event handles the request in the applicationafterAfter, but after returning the responsebeforeThe actual event name isafterRequest

When the event is triggered, the request has been processed. You can do some post-processing or custom response.

Note that the response component will also trigger some events when sending a response to the end user. These events are all in this eventafterTrigger after.

EVENT_BEFORE_ACTION

This event runs at each controller actionbeforeThe actual event is calledbeforeAction.

The parameter of the event is a Yii / base / ActionEvent instance. In event processing, you can set Yii / base / ActionEvent:: $isvalid tofalseStop running subsequent actions, such as:


[
 'on beforeAction' => function ($event) {
  if (some condition) {
   $event->isValid = false;
  } else {
  }
 },
]

Note that both the module and the controller will triggerbeforeActionevent. The event is triggered first by the application subject object, then by the module (if there is a module), and finally by the controller. In any event processing, set Yii / base / ActionEvent:: $isvalid tofalseWill stop triggering subsequent events.

EVENT_AFTER_ACTION

This event runs at each controller actionafterAfter that, the actual event is calledafterAction.

The parameter of this event is Yii / base / ActionEvent instance. Through the Yii / base / ActionEvent:: $result property, event processing can access and modify the result of the action. For example:

[
 'on afterAction' => function ($event) {
  if (some condition) {
   //Modify $event - > result
  } else {
  }
 },
]

Note that both the module and the controller will triggerafterActionevent. The order in which these objects are triggered andbeforeActionOn the contrary, that is to say, the controller triggers first, then the module (if there is a module), and finally the application body.

Application subject life cycle

Application Lifecycle

When a portal script is run to process the request, the application principal experiences the following lifecycle:

  1. The entry script loads the application body configuration array.
  2. The entry script creates an application principal instance:
    • Call preinit() to configure several high-level application principal properties, such as basepath.
    • Register error handler error handling method
    • Configure application principal properties
    • Call init () to initialize, which will call bootstrap () to run the bootstrap component
  3. The entry script calls Yii / base / application:: run() to run the application principal:
    • Trigger event_ BEFORE_ Request event.
    • Process request: resolve request route and related parameters; create module, controller and class corresponding to action specified by route, and run action.
    • Trigger event_ AFTER_ Request event.
    • Send the response to the end user
  4. The entry script receives the exit status from the application body and completes the processing of the request.

More about Yii related content interested readers can see the special topic: Yii framework introduction and common skills summary, PHP excellent development framework summary, smart template introduction basic tutorial, PHP object-oriented programming introduction tutorial, PHP string usage summary, PHP + MySQL database operation introduction tutorial and PHP common database operation Summary of writing skills

I hope that this article will be helpful to the PHP program design based on Yii framework.