- Request Lifecycle
- Entry scripts mainly do the following work
- Application Components
- Core Application Components
Request Lifecycle
- make a request to entry script(index.php).
- entry script loads the app.config and creates an application instance to handle the request.
- app can resolve requested route by request components like urlmanager
- Then app will create a controller instance.
- controller creates an action instance and performs the filters for the action.
- If any filter fails, the action is cancelled.
- If all filters pass, the action is executed.
- action loads a data model from database.
- action renders a view, providing it with the data model.
- The rendered result is returned to the response application component.
- The response component sends the rendered result to the user’s browser.
Entry scripts mainly do the following work
Web application and console application both have entry scripts like index.php
- Define global constants;
- Register Composer autoloader;
- Include the Yii class file;
- Load application configuration;
- Create and configure an application instance;
- Call yii\base\Application::run() to process the incoming request.
栗子 in web application
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
// register Composer autoloader
require(__DIR__ . '/../vendor/autoload.php');
// include Yii class file
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/../config/web.php');
// create, configure and run application
(new yii\web\Application($config))->run();
Application Components
we can access to components by \Yii::$app->componentID
,like \Yii::$app->db
.
- The following application configuration makes sure the log component is always loaded in every application:
[
'bootstrap' => [
'log',
],
'components' => [
'log' => [
// configuration for "log" component
],
],
]
Core Application Components
- db
- errorHandler
- log
- urlManager
- response
- request
- user
- view
- assetManager
- formatter
- i18n
- session
yii/base/application
/**
* Returns the configuration of core application components.
* @see set()
*/
public function coreComponents()
{
return [
'log' => ['class' => 'yii\log\Dispatcher'],
'view' => ['class' => 'yii\web\View'],
'formatter' => ['class' => 'yii\i18n\Formatter'],
'i18n' => ['class' => 'yii\i18n\I18N'],
'mailer' => ['class' => 'yii\swiftmailer\Mailer'],
'urlManager' => ['class' => 'yii\web\UrlManager'],
'assetManager' => ['class' => 'yii\web\AssetManager'],
'security' => ['class' => 'yii\base\Security'],
];
}pr