Applications
Applications are objects that govern the overall structure and lifecycle of Yii application systems.
Each Yii application system contains a single application object which is created in
the entry script and is globally accessible through the expression \Yii::$app
.
Info: Depending on the context, when we say "an application", it can mean either an application object or an application system.
There are two types of applications: [[yii\web\Application|Web applications]] and [[yii\console\Application|console applications]]. As the names indicate, the former mainly handles Web requests while the latter console command requests.
Application Configurations
When an entry script creates an application, it will load a configuration and apply it to the application, like the following:
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
// load application configuration
$config = require(__DIR__ . '/../config/web.php');
// instantiate and configure the application
(new yii\web\Application($config))->run();
Like normal configurations, application configurations specify how
to initialize properties of application objects. Because application configurations are often
very complex, they usually are kept in configuration files,
like the web.php
file in the above example.
Application Properties
There are many important application properties that you should configure in application configurations. These properties typically describe the environment that applications are running in. For example, applications need to know how to load controllers, where to store temporary files, etc. In the following, we will summarize these properties.
Required Properties
In any application, you should at least configure two properties: [[yii\base\Application::id|id]] and [[yii\base\Application::basePath|basePath]].
[[yii\base\Application::id|id]]
The [[yii\base\Application::id|id]] property specifies a unique ID that differentiates an application from others. It is mainly used programmatically. Although not a requirement, for best interoperability it is recommended that you use alphanumeric characters only when specifying an application ID.
[[yii\base\Application::basePath|basePath]]
The [[yii\base\Application::basePath|basePath]] property specifies the root directory of an application.
It is the directory that contains all protected source code of an application system. Under this directory,
you normally will see sub-directories such as models
, views
, controllers
, which contain source code
corresponding to the MVC pattern.
You may configure the [[yii\base\Application::basePath|basePath]] property using a directory path
or a path alias. In both forms, the corresponding directory must exist, or an exception
will be thrown. The path will be normalized by calling the realpath()
function.
The [[yii\base\Application::basePath|basePath]] property is often used to derive other important
paths (e.g. the runtime path). For this reason, a path alias named @app
is predefined to represent this
path. Derived paths may then be formed using this alias (e.g. @app/runtime
to refer to the runtime directory).
Important Properties
The properties described in this subsection often need to be configured because they differ across different applications.
[[yii\base\Application::aliases|aliases]]
This property allows you to define a set of aliases in terms of an array. The array keys are alias names, and the array values are the corresponding path definitions. For example,
[
'aliases' => [
'@name1' => 'path/to/path1',
'@name2' => 'path/to/path2',
],
]
This property is provided such that you can define aliases in terms of application configurations instead of the method calls [[Yii::setAlias()]].
[[yii\base\Application::bootstrap|bootstrap]]
This is a very useful property. It allows you to specify an array of components that should be run during the application [[yii\base\Application::bootstrap()|bootstrapping process]]. For example, if you want a module to customize the URL rules, you may list its ID as an element in this property.
Each component listed in this property may be specified in one of the following formats:
- an application component ID as specified via components.
- a module ID as specified via modules.
- a class name.
- a configuration array.
For example,
[
'bootstrap' => [
// an application component ID or module ID
'demo',
// a class name
'app\components\TrafficMonitor',
// a configuration array
[
'class' => 'app\components\Profiler',
'level' => 3,
]
],
]
During the bootstrapping process, each component will be instantiated. If the component class implements [[yii\base\BootstrapInterface]], its [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] method will be also be called.
Another practical example is in the application configuration for the Basic Application Template,
where the debug
and gii
modules are configured as bootstrap components when the application is running
in development environment,
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';
}
Note: Putting too many components in
bootstrap
will degrade the performance of your application because for each request, the same set of components need to be run. So use bootstrap components judiciously.
[[yii\web\Application::catchAll|catchAll]]
This property is supported by [[yii\web\Application|Web applications]] only. It specifies a controller action which should handle all user requests. This is mainly used when the application is in maintenance mode and needs to handle all incoming requests via a single action.
The configuration is an array whose first element specifies the route of the action. The rest of the array elements (key-value pairs) specify the parameters to be bound to the action. For example,
[
'catchAll' => [
'offline/notice',
'param1' => 'value1',
'param2' => 'value2',
],
]
[[yii\base\Application::components|components]]
This is the single most important property. It allows you to register a list of named components called application components that you can use in other places. For example,
[
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
],
]
Each application component is specified as a key-value pair in the array. The key represents the application ID, while the value represents the component class name or configuration.
You can register any component with an application, and the component can later be accessed globally
using the expression \Yii::$app->ComponentID
.
Please read the application components section for details.
[[yii\base\Application::controllerMap|controllerMap]]
This property allows you to map a controller ID to an arbitrary controller class. By default, Yii maps
controller IDs to controller classes based on a convention (e.g. the ID post
would be mapped
to app\controllers\PostController
). By configuring this property, you can break the convention for
specific controllers. In the following example, account
will be mapped to
app\controllers\UserController
, while article
will be mapped to app\controllers\PostController
.
[
'controllerMap' => [
[
'account' => 'app\controllers\UserController',
'article' => [
'class' => 'app\controllers\PostController',
'pageTitle' => 'something new',
],
],
],
]
The array keys of this property represent the controller IDs, while the array values represent the corresponding controller class names or configurations.
[[yii\base\Application::controllerNamespace|controllerNamespace]]
This property specifies the default namespace under which controller classes should be located. It defaults to
app\controllers
. If a controller ID is post
, by convention the corresponding controller class name (without
namespace) would be PostController
, and the fully qualified class name would be app\controllers\PostController
.
Controller classes may also be located under sub-directories of the directory corresponding to this namespace.
For example, given a controller ID admin/post
, the corresponding fully qualified controller class would
be app\controllers\admin\PostController
.
It is important that the fully qualified controller classes should be autoloadable and the actual namespace of your controller classes match the value of this property. Otherwise, you will receive "Page Not Found" error when accessing the application.
In case you want to break the convention as described above, you may configure the controllerMap property.
[[yii\base\Application::language|language]]
This property specifies the language in which the application should display content to end users. You should configure this property if your application needs to support multiple languages.
The value of this property determines various internationalization aspects,
including message translation, date formatting, number formatting, etc. For example, the [[yii\jui\DatePicker]] widget
will use this property value by default to determine in which language the calendar should be displayed and how
should the date be formatted. The default value of this property is en
.
It is recommended that you specify a language in terms of an IETF language tag.
For example, en
stands for English, while en-US
stands for English (United States).
More details about this property can be found in the Internationalization section.
[[yii\base\Application::modules|modules]]
This property specifies the modules that the application contains.
The property takes an array of module classes or configurations with the array keys being the module IDs. For example,
[
'modules' => [
// a "booking" module specified with the module class
'booking' => 'app\modules\booking\BookingModule',
// a "comment" module specified with a configuration array
'comment' => [
'class' => 'app\modules\comment\CommentModule',
'db' => 'db',
],
],
]
Please refer to the Modules section for more details.
[[yii\base\Application::name|name]]
This property specifies the application name that may be displayed to end users. Unlike the [[yii\base\Application::id|id]] property which should take a unique value, the value of this property is mainly for display purpose and does not need to be unique.
You do not always need to configure this property if none of your code is using it.
[[yii\base\Application::params|params]]
This property specifies an array of globally accessible application parameters. Instead of using hardcoded numbers and strings everywhere in your code, it is a good practice to define them as application parameters in a single place and use the parameters in places where needed. For example, you may define the thumbnail image size as a parameter like the following:
[
'params' => [
'thumbnail.size' => [128, 128],
],
]
Then in your code where you need to use the size value, you can simply use the code like the following:
$size = \Yii::$app->params['thumbnail.size'];
$width = \Yii::$app->params['thumbnail.size'][0];
Later if you decide to change the thumbnail size, you only need to modify it in the application configuration without touching any dependent code.
[[yii\base\Application::timeZone|timeZone]]
This property is provided as an alternative way of setting the default time zone of PHP runtime. By configuring this property, you are essentially calling the PHP function date_default_timezone_set(). For example,
[
'timeZone' => 'America/Los_Angeles',
]
[[yii\base\Application::version|version]]
This property specifies the version of the application. It defaults to '1.0'
. You do not always need to configure
this property if none of your code is using it.
Useful Properties
The properties described in this subsection are not commonly configured because their default values stipulate common conventions. However, you may still configure them in case you want to break the conventions.
[[yii\base\Application::charset|charset]]
This property specifies the charset that the application uses. The default value is 'UTF-8'
which should
be kept as is for most applications unless you are working with some legacy systems that use a lot of non-unicode data.
[[yii\base\Application::defaultRoute|defaultRoute]]
This property specifies the route that an application should use when a request
does not specify one. The route may consist of child module ID, controller ID, and/or action ID.
For example, help
, post/create
, admin/post/create
. If action ID is not given, it will take the default
value as specified in [[yii\base\Controller::defaultAction]].
For [yii\web\Application|Web applications], the default value of this property is 'site'
, which means
the SiteController
controller and its default action should be used. As a result, if you access
the application without specifying a route, it will show the result of app\controllers\SiteController::actionIndex()
.
For [yii\console\Application|console applications], the default value is 'help'
, which means the core command
[[yii\console\controllers\HelpController::actionIndex()]] should be used. As a result, if you run the command yii
without providing any arguments, it will display the help information.
[[yii\base\Application::extensions|extensions]]
This property specifies the list of extensions that are installed and used by the application.
By default, it will take the array returned by the file @vendor/yiisoft/extensions.php
. The extensions.php
file
is generated and maintained automatically when you use Composer to install extensions.
So in most cases, you do not need to configure this property.
In the special case when you want to maintain extensions manually, you may configure this property like the following:
[
'extensions' => [
[
'name' => 'extension name',
'version' => 'version number',
'bootstrap' => 'BootstrapClassName', // optional, may also be a configuration array
'alias' => [ // optional
'@alias1' => 'to/path1',
'@alias2' => 'to/path2',
],
],
// ... more extensions like the above ...
],
]
As you can see, the property takes an array of extension specifications. Each extension is specified with an array
consisting of name
and version
elements. If an extension needs to run during the bootstrap
property, a bootstrap
element may be specified with a bootstrap class name or a configuration
array. An extension may also define a few aliases.
[[yii\base\Application::layout|layout]]
[[yii\base\Application::layoutPath|layoutPath]]
[[yii\base\Application::runtimePath|runtimePath]]
[[yii\base\Application::sourceLanguage|sourceLanguage]]
[[yii\base\Application::viewPath|viewPath]]
[[yii\base\Application::vendorPath|vendorPath]]
[[yii\console\Application::enableCoreCommands|enableCoreCommands]]
Application Components
Applications are service locators. They host a set of the so-called
application components that provide different services for request processing. For example,
the urlManager
component is responsible for routing Web requests to appropriate controllers;
the db
component provides DB-related services; and so on.
Each application component has an ID that uniquely identifies itself among other application components
in the same application. You can access an application component through the expression $app->ID
,
where $app
refers to an application instance, and ID
stands for the ID of an application component.
For example, you can use Yii::$app->db
to get the [[yii\db\Connection|DB connection]], and Yii::$app->cache
to get the [[yii\caching\Cache|primary cache]] registered with the application.
Application components can be any objects. You can register them with an application to make them globally accessible. This is usually done by configuring the [[yii\base\Application::components]] property, as described in the components subsection.
Yii predefines a set of core application components to provide features common among different applications. For example, the [[yii\web\Application::request|request]] component is used to collect information about a user request and resolve it into a route. By configuring the properties of these core components, you can customize nearly every aspect of Yii.
Below is the list of the predefined core application components:
[assetManager|CWebApplication::assetManager]: [CAssetManager] - manages the publishing of private asset files.
[authManager|CWebApplication::authManager]: [CAuthManager] - manages role-based access control (RBAC).
[cache|CApplication::cache]: [CCache] - provides data caching functionality. Note, you must specify the actual class (e.g. [CMemCache], [CDbCache]). Otherwise, null will be returned when you access this component.
[clientScript|CWebApplication::clientScript]: [CClientScript] - manages client scripts (javascript and CSS).
[coreMessages|CApplication::coreMessages]: [CPhpMessageSource] - provides translated core messages used by the Yii framework.
[db|CApplication::db]: [CDbConnection] - provides the database connection. Note, you must configure its [connectionString|CDbConnection::connectionString] property in order to use this component.
[errorHandler|CApplication::errorHandler]: [CErrorHandler] - handles uncaught PHP errors and exceptions.
[format|CApplication::format]: [CFormatter] - formats data values for display purpose.
[messages|CApplication::messages]: [CPhpMessageSource] - provides translated messages used by the Yii application.
[request|CWebApplication::request]: [CHttpRequest] - provides information related to user requests.
[securityManager|CApplication::securityManager]: [CSecurityManager] - provides security-related services, such as hashing and encryption.
[session|CWebApplication::session]: [CHttpSession] - provides session-related functionality.
[statePersister|CApplication::statePersister]: [CStatePersister] - provides the mechanism for persisting global state.
[urlManager|CWebApplication::urlManager]: [CUrlManager] - provides URL parsing and creation functionality.
[user|CWebApplication::user]: [CWebUser] - carries identity-related information about the current user.
[themeManager|CWebApplication::themeManager]: [CThemeManager] - manages themes.
Application Lifecycle
When handling a user request, an application will undergo the following life cycle:
Pre-initialize the application with [CApplication::preinit()];
Set up the error handling;
Register core application components;
Load application configuration;
-
Initialize the application with [CApplication::init()]
- Register application behaviors;
- Load static application components;
Raise an [onBeginRequest|CApplication::onBeginRequest] event;
-
Process the user request:
- Collect information about the request;
- Create a controller;
- Run the controller;
Raise an [onEndRequest|CApplication::onEndRequest] event;