Skip to content
PHP Ecosystem
Explore

Application

API reference › yii › base › Application

abstract classyii\base\Application
ExtendsModule » yii\di\ServiceLocator » Component » BaseObject
ImplementsConfigurable
Since2.0
Sourceframework/base/Application.php
2 subclasses

Application is the base class for all application classes.

For more details and usage information on Application, see the guide article on applications.

PropertyTypeDescriptionDefined by
$actionMaparray<string, class-string|array<string, mixed>>Mapping from action IDs to standalone Action class configurations. Default: []. Available since 22.0.Module
$actionNamespacestring|nullThe namespace where standalone Action subclasses are located for convention-based discovery, parallel to $controllerNamespace for controllers. Default: null. Available since 22.0.Module
$aliases write-onlyarrayList of path aliases to be defined.Module
$assetManager read-onlyyii\web\AssetManagerThe asset manager application component.Application
$authManager read-onlyyii\rbac\ManagerInterface|nullThe auth manager application component or null if it’s not configured.Application
$basePathstringThe root directory of the application.Application
$behaviors read-onlyarray<Behavior<static>>List of behaviors attached to this component.Component
$bootstraparrayList of components that should be run during the application bootstrapping process. Default: [].Application
$cache read-onlyyii\caching\CacheInterface|nullThe cache application component.Application
$charsetstringThe charset currently used for the application. Default: 'UTF-8'.Application
$componentsarrayThe list of the component definitions or the loaded component instances (ID => definition or instance).yii\di\ServiceLocator
$container write-onlyarrayValues given in terms of name-value pairs.Application
$controllerController|nullThe currently active controller instance Default: null.Application
$controllerMaparrayMapping from controller ID to controller configurations. Default: [].Module
$controllerNamespacestringThe namespace that controller classes are located in. Default: 'app\controllers'.Application
$controllerPathstringThe directory that contains the controller classes.Module
$db read-onlyyii\db\ConnectionThe database connection.Application
$defaultRoutestringThe default route of this module. Default: 'default'.Module
$errorHandler read-onlyyii\web\ErrorHandler|yii\console\ErrorHandlerThe error handler application component.Application
$extensionsarray|nullList of installed Yii extensions. Default: null.Application
$formatter read-onlyyii\i18n\FormatterThe formatter application component.Application
$i18n read-onlyyii\i18n\I18NThe internationalization application component.Application
$idstringAn ID that uniquely identifies this module among other modules which have the same parent. Default: null.Module
$languagestringThe language that is meant to be used for end users. Default: 'en-US'.Application
$layoutstring|boolThe layout that should be applied for views in this application. Default: 'main'.Application
$layoutPathstringThe root directory of layout files.Module
$loadedModulesarrayList of loaded modules indexed by their class names. Default: [].Application
$log read-onlyyii\log\DispatcherThe log dispatcher application component.Application
$mailer read-onlyyii\mail\MailerInterfaceThe mailer application component.Application
$moduleModule|nullThe parent module of this module. null if this module does not have a parent. Default: null.Module
$modulesarrayThe modules (indexed by their IDs).Module
$namestringThe application name. Default: 'My Application'.Application
$paramsarrayCustom module parameters (name => value). Default: [].Module
$request read-onlyyii\web\Request|yii\console\RequestThe request component.Application
$requestedActionAction<Controller>|nullThe requested Action. Default: null.Application
$requestedParamsarray|nullThe parameters supplied to the requested action. Default: null.Application
$requestedRoutestringThe requested route Default: null.Application
$response read-onlyyii\web\Response|yii\console\ResponseThe response component.Application
$runtimePathstringThe directory that stores runtime files.Application
$security read-onlySecurityThe security application component.Application
$sourceLanguagestringThe language that the application is written in. Default: 'en-US'.Application
$stateintThe current application state during a request handling life cycle. Default: null.Application
$timeZonestringThe time zone used by this application.Application
$uniqueId read-onlystringThe unique ID of the module.Application
$urlManager read-onlyyii\web\UrlManagerThe URL manager for this application.Application
$vendorPathstringThe directory that stores vendor files.Application
$versionstring|callable|nullThe version of this module.Module
$view read-onlyView|yii\web\ViewThe view application component that is used to render various view files.Application
$viewPathstringThe root directory of view files.Module
MethodDescriptionDefined by
__construct()Constructor.Application
__call()Calls the named method which is not a class method.Component
__clone()This method is called after the object is created by cloning an existing one.Component
__get()Getter magic method.yii\di\ServiceLocator
__isset()Checks if a property value is null.yii\di\ServiceLocator
__set()Sets the value of a component property.Component
__unset()Sets a component property to be null.Component
afterAction()This method is invoked right after an action within this module is executed.Module
attachBehavior()Attaches a behavior to this component.Component
attachBehaviors()Attaches a list of behaviors to the component.Component
beforeAction()This method is invoked right before an action within this module is executed.Module
behaviors()Returns a list of behaviors that this component should behave as.Component
canGetProperty()Returns a value indicating whether a property can be read.Component
canSetProperty()Returns a value indicating whether a property can be set.Component
className() staticReturns the fully qualified name of this class.BaseObject
clear()Removes the component from the locator.yii\di\ServiceLocator
coreComponents()Returns the configuration of core application components.Application
createController()Creates a controller instance based on the given route.Module
createControllerByID()Creates a controller based on the given controller ID.Module
detachBehavior()Detaches a behavior from the component.Component
detachBehaviors()Detaches all behaviors from the component.Component
end()Terminates the application.Application
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.Component
get()Returns the component instance with the specified ID.Module
getAssetManager()Returns the asset manager.Application
getAuthManager()Returns the auth manager for this application.Application
getBasePath()Returns the root directory of the module.Module
getBehavior()Returns the named behavior object.Component
getBehaviors()Returns all behaviors attached to this component.Component
getCache()Returns the cache component.Application
getComponents()Returns the list of the component definitions or the loaded component instances.yii\di\ServiceLocator
getControllerPath()Returns the directory that contains the controller classes according to $controllerNamespace.Module
getDb()Returns the database connection component.Application
getErrorHandler()Returns the error handler component.Application
getFormatter()Returns the formatter component.Application
getI18n()Returns the internationalization (i18n) component.Application
getInstance() staticReturns the currently requested instance of this module class.Module
getLayoutPath()Returns the directory that contains layout view files for this module.Module
getLog()Returns the log dispatcher component.Application
getMailer()Returns the mailer component.Application
getModule()Retrieves the child module of the specified ID.Module
getModules()Returns the sub-modules in this module.Module
getRequest()Returns the request component.Application
getResponse()Returns the response component.Application
getRuntimePath()Returns the directory that stores runtime files.Application
getSecurity()Returns the security component.Application
getTimeZone()Returns the time zone used by this application.Application
getUniqueId()Returns an ID that uniquely identifies this module among all modules within the current application.Application
getUrlManager()Returns the URL manager for this application.Application
getVendorPath()Returns the directory that stores vendor files.Application
getVersion()Returns current module version.Module
getView()Returns the view object.Application
getViewPath()Returns the directory that contains the view files for this module.Module
handleRequest() abstractHandles the specified request.Application
has()Returns a value indicating whether the locator has the specified component definition or has instantiated the component.Module
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.Component
hasMethod()Returns a value indicating whether a method is defined.Component
hasModule()Checks whether the child module of the specified ID exists.Module
hasProperty()Returns a value indicating whether a property is defined for this component.Component
init()Initializes the module.Application
off()Detaches an existing event handler from this component.Component
on()Attaches an event handler to an event.Component
preInit()Pre-initializes the application.Application
run()Runs the application.Application
runAction()Runs a controller action specified by a route.Module
set()Registers a component definition with this locator.yii\di\ServiceLocator
setAliases()Defines path aliases.Module
setBasePath()Sets the root directory of the application and the @app alias.Application
setComponents()Registers a set of component definitions in this locator.yii\di\ServiceLocator
setContainer()Configures Yii::$container with the $config.Application
setControllerPath()Sets the directory that contains the controller classes.Module
setInstance() staticSets the currently requested instance of this module class.Module
setLayoutPath()Sets the directory that contains the layout files.Module
setModule()Adds a sub-module to this module.Module
setModules()Registers sub-modules in the current module.Module
setRuntimePath()Sets the directory that stores runtime files.Application
setTimeZone()Sets the time zone used by this application.Application
setVendorPath()Sets the directory that stores vendor files.Application
setVersion()Sets current module version.Module
setViewPath()Sets the directory that contains the view files.Module
trigger()Triggers an event.Component
bootstrap() protectedInitializes extensions and executes bootstrap components.Application
createStandaloneAction() protectedResolves a route to a standalone Action class through convention-based discovery under $actionNamespace.Module
defaultVersion() protectedReturns default module version.Module
registerErrorHandler() protectedRegisters the errorHandler component as a PHP error handler.Application
runMappedAction() protectedRuns a standalone action registered in $actionMap.Module
runStandaloneAction() protectedRuns a standalone Action instance through the standard module/action event lifecycle.Module
EventTypeDescriptionDefined by
EVENT_BEFORE_REQUESTEventAn event raised before the application starts to handle a request. Event name: 'beforeRequest'.Application
EVENT_AFTER_REQUESTEventAn event raised after the application successfully handles a request (before the response is sent out). Event name: 'afterRequest'.Application
EVENT_BEFORE_ACTIONActionEventAn event raised before executing a controller action. Event name: 'beforeAction'.Module
EVENT_AFTER_ACTIONActionEventAn event raised after executing a controller action. Event name: 'afterAction'.Module
ConstantValueDescriptionDefined by
STATE_BEGIN0Application state used by $state: application just started.Application
STATE_INIT1Application state used by $state: application is initializing.Application
STATE_BEFORE_REQUEST2Application state used by $state: application is triggering EVENT_BEFORE_REQUEST.Application
STATE_HANDLING_REQUEST3Application state used by $state: application is handling the request.Application
STATE_AFTER_REQUEST4Application state used by $state: application is triggering EVENT_AFTER_REQUEST.Application
STATE_SENDING_RESPONSE5Application state used by $state: application is about to send response.Application
STATE_END6Application state used by $state: application has ended.Application
public array $bootstrap = []

List of components that should be run during the application bootstrapping process.

Each component 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.
  • a Closure

During the bootstrapping process, each component will be instantiated. If the component class implements BootstrapInterface, its bootstrap() method will be also be called.

public yii\caching\CacheInterface|null $cache

The cache application component.

Null if the component is not enabled.

Access

Read-only (virtual property).

public string $controllerNamespace = 'app\controllers'

The namespace that controller classes are located in.

This namespace will be used to load controller classes by prepending it to the controller class name. The default namespace is app\controllers.

Please refer to the guide about class autoloading for more details.

public array|null $extensions = null

List of installed Yii extensions.

Each array element represents a single extension with the following structure:

[
'name' => 'extension name',
'version' => 'version number',
'bootstrap' => 'BootstrapClassName', // optional, may also be a configuration array
'alias' => [
'@alias1' => 'to/path1',
'@alias2' => 'to/path2',
],
]

The “bootstrap” class listed above will be instantiated during the application bootstrapping process. If the class implements BootstrapInterface, its bootstrap() method will be also be called.

If not set explicitly in the application config, this property will be populated with the contents of @vendor/yiisoft/extensions.php.

public string $language = 'en-US'

The language that is meant to be used for end users.

It is recommended that you use IETF language tags. For example, en stands for English, while en-US stands for English (United States).

public string|bool $layout = 'main'

The layout that should be applied for views in this application.

Defaults to ‘main’. If this is false, layout will be disabled.

public yii\base\Action<yii\base\Controller>|null $requestedAction = null

The requested Action.

If null, it means the request cannot be resolved into an action.

public string $runtimePath

The directory that stores runtime files.

Defaults to the “runtime” subdirectory under $basePath.

public string $sourceLanguage = 'en-US'

The language that the application is written in.

This mainly refers to the language that the messages and view files are written in.

public int $state = null

The current application state during a request handling life cycle.

This property is managed by the application. Do not modify this property.

public string $vendorPath

The directory that stores vendor files.

Defaults to “vendor” directory under $basePath.

public function __construct(array<array-key, mixed> $config = [])

Constructor.

Parameters

ParameterTypeDescription
$configarray<array-key, mixed>Name-value pairs that will be used to initialize the object properties. Note that the configuration must contain both $id and $basePath.

Throws

public function coreComponents(): array

Returns the configuration of core application components.

Returns

array

See also

public function end(int $status = 0, yii\base\Response|null $response = null): mixed

Terminates the application.

This method replaces the exit() function by ensuring the application life cycle is completed before terminating the application.

Parameters

ParameterTypeDescription
$statusintThe exit status (value 0 means normal exit while other values mean abnormal exit).
$responseResponse|nullThe response to be sent. If not set, the default application $response component will be used.

Returns

mixed

Throws

public function getAssetManager(): yii\web\AssetManager

Returns the asset manager.

Returns

yii\web\AssetManager: The asset manager application component.

public function getAuthManager(): yii\rbac\ManagerInterface|null

Returns the auth manager for this application.

Returns

yii\rbac\ManagerInterface|null: The auth manager application component or null if it’s not configured.

public function getCache(): yii\caching\CacheInterface|null

Returns the cache component.

Returns

yii\caching\CacheInterface|null: The cache application component. Null if the component is not enabled.

public function getDb(): yii\db\Connection

Returns the database connection component.

Returns

yii\db\Connection: The database connection.

public function getErrorHandler(): yii\web\ErrorHandler|yii\console\ErrorHandler

Returns the error handler component.

Returns

yii\web\ErrorHandler|yii\console\ErrorHandler: The error handler application component.

public function getFormatter(): yii\i18n\Formatter

Returns the formatter component.

Returns

yii\i18n\Formatter: The formatter application component.

public function getI18n(): yii\i18n\I18N

Returns the internationalization (i18n) component.

Returns

yii\i18n\I18N: The internationalization application component.

public function getLog(): yii\log\Dispatcher

Returns the log dispatcher component.

Returns

yii\log\Dispatcher: The log dispatcher application component.

public function getMailer(): yii\mail\MailerInterface

Returns the mailer component.

Returns

yii\mail\MailerInterface: The mailer application component.

Throws

public function getRequest(): yii\web\Request|yii\console\Request

Returns the request component.

Returns

yii\web\Request|yii\console\Request: The request component.

public function getResponse(): yii\web\Response|yii\console\Response

Returns the response component.

Returns

yii\web\Response|yii\console\Response: The response component.

public function getRuntimePath(): string

Returns the directory that stores runtime files.

Returns

string: The directory that stores runtime files. Defaults to the “runtime” subdirectory under $basePath.

public function getSecurity(): yii\base\Security

Returns the security component.

Returns

Security: The security application component.

public function getTimeZone(): string

Returns the time zone used by this application.

This is a simple wrapper of PHP function date_default_timezone_get(). If time zone is not configured in php.ini or application config, it will be set to UTC by default.

Returns

string: The time zone used by this application.

See also

public function getUniqueId(): string

Returns an ID that uniquely identifies this module among all modules within the current application.

Since this is an application instance, it will always return an empty string.

Returns

string: The unique ID of the module.

public function getUrlManager(): yii\web\UrlManager

Returns the URL manager for this application.

Returns

yii\web\UrlManager: The URL manager for this application.

public function getVendorPath(): string

Returns the directory that stores vendor files.

Returns

string: The directory that stores vendor files. Defaults to “vendor” directory under $basePath.

public function getView(): yii\base\View|yii\web\View

Returns the view object.

Returns

View|yii\web\View: The view application component that is used to render various view files.

abstract public function handleRequest(yii\base\Request $request): yii\base\Response

Handles the specified request.

This method should return an instance of Response or its child class which represents the handling result of the request.

Parameters

ParameterTypeDescription
$requestRequestThe request to be handled

Returns

Response: The resulting response

public function init(): mixed

Initializes the module.

This method is called after the module is created and initialized with property values given in configuration.

The default implementation will initialize $controllerNamespace if it is not set.

If you override this method, please make sure you call the parent implementation.

Returns

mixed

public function preInit(array &$config): mixed

Pre-initializes the application.

This method is called at the beginning of the application constructor. It initializes several important application properties. If you override this method, please make sure you call the parent implementation.

Parameters

ParameterTypeDescription
$configarrayThe application configuration

Returns

mixed

Throws

public function run(): int

Runs the application.

This is the main entrance of an application.

Returns

int: The exit status (0 means normal, non-zero values mean abnormal)

public function setBasePath(string $path): mixed

Sets the root directory of the application and the @app alias.

This method can only be invoked at the beginning of the constructor.

Parameters

ParameterTypeDescription
$pathstringThe root directory of the application.

Returns

mixed

Throws

public function setContainer(array $config): mixed

Configures Yii::$container with the $config.

Parameters

ParameterTypeDescription
$configarrayValues given in terms of name-value pairs

Returns

mixed

Since

2.0.11

public function setRuntimePath(string $path): mixed

Sets the directory that stores runtime files.

Parameters

ParameterTypeDescription
$pathstringThe directory that stores runtime files.

Returns

mixed

public function setTimeZone(string $value): mixed

Sets the time zone used by this application.

This is a simple wrapper of PHP function date_default_timezone_set(). Refer to the php manual for available timezones.

Parameters

ParameterTypeDescription
$valuestringThe time zone used by this application.

Returns

mixed

See also

public function setVendorPath(string $path): mixed

Sets the directory that stores vendor files.

Parameters

ParameterTypeDescription
$pathstringThe directory that stores vendor files.

Returns

mixed

protected function bootstrap(): mixed

Initializes extensions and executes bootstrap components.

This method is called by init() after the application has been fully configured. If you override this method, make sure you also call the parent implementation.

Returns

mixed

protected function registerErrorHandler(array &$config): mixed

Registers the errorHandler component as a PHP error handler.

Parameters

ParameterTypeDescription
$configarrayApplication config

Returns

mixed