Skip to content
PHP Ecosystem
Explore

Module

API reference › yii › base › Module

classyii\base\Module
Extendsyii\di\ServiceLocator » Component » BaseObject
ImplementsConfigurable
Since2.0
Sourceframework/base/Module.php
2 subclasses

Module is the base class for module and application classes.

A module represents a sub-application which contains MVC elements by itself, such as models, views, controllers, etc.

A module may consist of sub-modules.

Components may be registered with the module so that they are globally accessible within the module.

For more details and usage information on Module, see the guide article on modules.

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
$basePathstringThe root directory of the module.Module
$behaviors read-onlyarray<Behavior<static>>List of behaviors attached to this component.Component
$componentsarrayThe list of the component definitions or the loaded component instances (ID => definition or instance).yii\di\ServiceLocator
$controllerMaparrayMapping from controller ID to controller configurations. Default: [].Module
$controllerNamespacestring|nullThe namespace that controller classes are in. Default: null.Module
$controllerPathstringThe directory that contains the controller classes.Module
$defaultRoutestringThe default route of this module. Default: 'default'.Module
$idstringAn ID that uniquely identifies this module among other modules which have the same parent. Default: null.Module
$layoutstring|bool|nullThe layout that should be applied for views within this module. Default: null.Module
$layoutPathstringThe root directory of layout files.Module
$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
$paramsarrayCustom module parameters (name => value). Default: [].Module
$uniqueId read-onlystringThe unique ID of the module.Module
$versionstring|callable|nullThe version of this module.Module
$viewPathstringThe root directory of view files.Module
MethodDescriptionDefined by
__construct()Constructor.Module
__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
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
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
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
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
getInstance() staticReturns the currently requested instance of this module class.Module
getLayoutPath()Returns the directory that contains layout view files for this module.Module
getModule()Retrieves the child module of the specified ID.Module
getModules()Returns the sub-modules in this module.Module
getUniqueId()Returns an ID that uniquely identifies this module among all modules within the current application.Module
getVersion()Returns current module version.Module
getViewPath()Returns the directory that contains the view files for this module.Module
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.Module
off()Detaches an existing event handler from this component.Component
on()Attaches an event handler to an event.Component
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 module.Module
setComponents()Registers a set of component definitions in this locator.yii\di\ServiceLocator
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
setVersion()Sets current module version.Module
setViewPath()Sets the directory that contains the view files.Module
trigger()Triggers an event.Component
createStandaloneAction() protectedResolves a route to a standalone Action class through convention-based discovery under $actionNamespace.Module
defaultVersion() protectedReturns default module version.Module
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_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
public array<string, class-string|array<string, mixed>> $actionMap = []

Mapping from action IDs to standalone Action class configurations.

Mapped actions are dispatched by runAction() without requiring a hosting controller, in parallel to $controllerMap.

Each entry maps an ID (the first route segment) to either a fully qualified class name or an array configuration accepted by Yii::createObject(). The class must extend Action.

Usage example:

[
'webhooks-stripe' => app\actions\StripeWebhookAction::class,
'health' => ['class' => app\actions\HealthCheckAction::class],
]

Action IDs in this map take precedence over IDs in $controllerMap and over module/controller resolution.

Routes whose first segment is not present here fall through to the legacy controller pipeline unchanged.

Resolution scope: this map is consulted only by the module whose runAction() handles the route (typically the application). Unlike $controllerMap, it is NOT resolved recursively across sub-modules during nested-route dispatch. To expose a standalone action under a sub-module, rely on $actionNamespace (which IS resolved recursively), or register the action in the dispatching module’s $actionMap.

Since

22.0

public string|null $actionNamespace = null

The namespace where standalone Action subclasses are located for convention-based discovery, parallel to $controllerNamespace for controllers.

If not set, defaults to the value of $controllerNamespace during init(), so standalone actions can live next to controllers under the same root. Set this property to a different namespace to organize standalone actions in their own folder (for example, vertical slices under app\UseCase):

Usage example:

'actionNamespace' => 'app\\UseCase',

With the example above, route posts/index resolves to app\UseCase\posts\IndexAction, route posts/view-summary resolves to app\UseCase\posts\ViewSummaryAction, and so on. The same hyphen, slash, and CamelCase rules apply as for controllers (see createControllerByID()).

Resolution order in runAction(): explicit $controllerMap/$actionMap entries are checked first, then sub-modules, then controllers by namespace, and finally standalone actions by namespace. When a controller method AND a standalone Action class both match the same route, runAction() throws InvalidConfigException so the developer disambiguates instead of silently shadowing one or the other.

Since

22.0

public array $aliases

List of path aliases to be defined.

The array keys are alias names (must start with @) and the array values are the corresponding paths or aliases. For example,

[
'@models' => '@app/models', // an existing alias
'@backend' => __DIR__ . '/../backend', // a directory
]

Access

Write-only (virtual property).

public array $controllerMap = []

Mapping from controller ID to controller configurations.

Each name-value pair specifies the configuration of a single controller. A controller configuration can be either a string or an array. If the former, the string should be the fully qualified class name of the controller. If the latter, the array must contain a class element which specifies the controller’s fully qualified class name, and the rest of the name-value pairs in the array are used to initialize the corresponding controller properties. For example,

[
'account' => 'app\controllers\UserController',
'article' => [
'class' => 'app\controllers\PostController',
'pageTitle' => 'something new',
],
]
public string|null $controllerNamespace = null

The namespace that controller classes are in.

This namespace will be used to load controller classes by prepending it to the controller class name.

If not set, it will use the controllers sub-namespace under the namespace of this module. For example, if the namespace of this module is foo\bar, then the default controller namespace would be foo\bar\controllers.

See also the guide section on autoloading to learn more about defining namespaces and how classes are loaded.

public string $defaultRoute = 'default'

The default route of this module.

Defaults to default. 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 Controller::$defaultAction.

public string|bool|null $layout = null

The layout that should be applied for views within this module.

This refers to a view name relative to $layoutPath. If this is not set, it means the layout value of the parent module will be taken. If this is false, layout will be disabled within this module.

public string $layoutPath

The root directory of layout files.

Defaults to “$viewPath/layouts”.

public string|callable|null $version

The version of this module.

Version can be specified as a PHP callback, which can accept module instance as an argument and should return the actual version. For example:

function (Module $module) {
//return string
}
public string $viewPath

The root directory of view files.

Defaults to “$basePath/views”.

public function __construct(string $id, yii\base\Module|null $parent = null, array<string, mixed> $config = [])

Constructor.

Parameters

ParameterTypeDescription
$idstringThe ID of this module.
$parentModule|nullThe parent module (if any).
$configarray<string, mixed>Name-value pairs that will be used to initialize the object properties.
public function afterAction(yii\base\Action<yii\base\Controller<static>> $action, mixed $result): mixed

This method is invoked right after an action within this module is executed.

The method will trigger the EVENT_AFTER_ACTION event. The return value of the method will be used as the action return value.

If you override this method, your code should look like the following:

public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
return $result;
}

Parameters

ParameterTypeDescription
$actionAction<Controller<static>>The action just executed.
$resultmixedThe action return result.

Returns

mixed: The processed action result.

public function beforeAction(yii\base\Action<yii\base\Controller<static>> $action): bool

This method is invoked right before an action within this module is executed.

The method will trigger the EVENT_BEFORE_ACTION event. The return value of the method will determine whether the action should continue to run.

In case the action should not run, the request should be handled inside of the beforeAction code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.

If you override this method, your code should look like the following:

public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
// your custom code here
return true; // or false to not run the action
}

Parameters

ParameterTypeDescription
$actionAction<Controller<static>>The action to be executed.

Returns

bool: Whether the action should continue to be executed.

public function createController(string $route): array{yii\base\Controller<static>, string}|false

Creates a controller instance based on the given route.

The route should be relative to this module. The method implements the following algorithm to resolve the given route:

  1. If the route is empty, use $defaultRoute;
  2. If the first segment of the route is found in $controllerMap, create a controller based on the corresponding configuration found in $controllerMap;
  3. If the first segment of the route is a valid module ID as declared in $modules, call the module’s createController() with the rest part of the route;
  4. The given route is in the format of abc/def/xyz. Try either abc\DefController or abc\def\XyzController class within the controller namespace.

If any of the above steps resolves into a controller, it is returned together with the rest part of the route which will be treated as the action ID. Otherwise, false will be returned.

Parameters

ParameterTypeDescription
$routestringThe route consisting of module, controller and action IDs.

Returns

array{Controller<static>, string}|false: If the controller is created successfully, it will be returned together with the requested action ID. Otherwise false will be returned.

Throws

public function createControllerByID(string $id): yii\base\Controller<static>|null

Creates a controller based on the given controller ID.

The controller ID is relative to this module. The controller class should be namespaced under $controllerNamespace.

Note that this method does not check $modules or $controllerMap.

Parameters

ParameterTypeDescription
$idstringThe controller ID.

Returns

Controller<static>|null: The newly created controller instance, or null if the controller ID is invalid.

Throws

  • InvalidConfigException: if the controller class and its file name do not match. This exception is only thrown when in debug mode.
public function get(mixed $id, mixed $throwException = true): ($throwException is true ? object : object|null)

Returns the component instance with the specified ID.

Since version 2.0.13, if a component isn’t defined in the module, it will be looked up in the parent module. The parent module may be the application.

Parameters

ParameterTypeDescription
$idmixedComponent ID (e.g. db).
$throwExceptionmixedWhether to throw an exception if $id is not registered with the locator before.

Returns

($throwException is true ? object : object|null): The component of the specified ID. If $throwException is false and $id is not registered before, null will be returned.

Throws

public function getBasePath(): string

Returns the root directory of the module.

It defaults to the directory containing the module class file.

Returns

string: The root directory of the module.

public function getControllerPath(): string

Returns the directory that contains the controller classes according to $controllerNamespace.

Note that in order for this method to return a value, you must define an alias for the root namespace of $controllerNamespace.

Returns

string: The directory that contains the controller classes.

Throws

public static function getInstance(): static|null

Returns the currently requested instance of this module class.

If the module class is not currently requested, null will be returned. This method is provided so that you access the module instance from anywhere within the module.

Returns

static|null: The currently requested instance of this module class, or null if the module class is not requested.

public function getLayoutPath(): string

Returns the directory that contains layout view files for this module.

Returns

string: The root directory of layout files. Defaults to “$viewPath/layouts”.

public function getModule(string $id, bool $load = true): yii\base\Module|null

Retrieves the child module of the specified ID.

This method supports retrieving both child modules and grand child modules.

Parameters

ParameterTypeDescription
$idstringModule ID (case-sensitive). To retrieve grand child modules, use ID path relative to this module (e.g. admin/content).
$loadboolWhether to load the module if it is not yet loaded.

Returns

Module|null: The module instance, null if the module does not exist.

See also

public function getModules(bool $loadedOnly = false): array

Returns the sub-modules in this module.

Parameters

ParameterTypeDescription
$loadedOnlyboolWhether to return the loaded sub-modules only. If this is set false, then all sub-modules registered in this module will be returned, whether they are loaded or not. Loaded modules will be returned as objects, while unloaded modules as configuration arrays.

Returns

array: The modules (indexed by their IDs).

public function getUniqueId(): string

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

Note that if the module is an application, an empty string will be returned.

Returns

string: The unique ID of the module.

public function getVersion(): string

Returns current module version.

If version is not explicitly set, defaultVersion() method will be used to determine its value.

Returns

string: The version of this module.

Since

2.0.11

public function getViewPath(): string

Returns the directory that contains the view files for this module.

Returns

string: The root directory of view files. Defaults to “$basePath/views”.

public function has(mixed $id, mixed $checkInstance = false): bool

Returns a value indicating whether the locator has the specified component definition or has instantiated the component.

Since version 2.0.13, if a component isn’t defined in the module, it will be looked up in the parent module. The parent module may be the application.

This method may return different results depending on the value of $checkInstance.

  • If $checkInstance is false (default), the method will return a value indicating whether the locator has the specified component definition.
  • If $checkInstance is true, the method will return a value indicating whether the locator has instantiated the specified component.

Parameters

ParameterTypeDescription
$idmixedComponent ID (e.g. db).
$checkInstancemixedWhether the method should check if the component is shared and instantiated.

Returns

bool: Whether the locator has the specified component definition or has instantiated the component.

public function hasModule(string $id): bool

Checks whether the child module of the specified ID exists.

This method supports checking the existence of both child and grand child modules.

Parameters

ParameterTypeDescription
$idstringModule ID. For grand child modules, use ID path relative to this module (e.g. admin/content).

Returns

bool: Whether the named module exists. Both loaded and unloaded modules are considered.

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 runAction(string $route, array $params = []): mixed

Runs a controller action specified by a route.

This method parses the specified route and creates the corresponding child module(s), controller and action instances. It then calls Controller::runAction() to run the action with the given parameters.

If the route is empty, the method will use $defaultRoute.

Since version 22.0, when the first segment of the route matches a key in $actionMap, the action is dispatched as a standalone action via runMappedAction(), without resolving a controller. When no controller resolves the route either, the method falls back to convention-based standalone action lookup under $actionNamespace via createStandaloneAction(). When a controller method AND a standalone Action class both match the same route, the method throws InvalidConfigException so the developer disambiguates instead of silently shadowing one or the other.

Parameters

ParameterTypeDescription
$routestringThe route that specifies the action.
$paramsarrayThe parameters to be passed to the action.

Returns

mixed: The result of the action.

Throws

public function setAliases(array $aliases): mixed

Defines path aliases.

This method calls Yii::setAlias() to register the path aliases. This method is provided so that you can define path aliases when configuring a module.

Parameters

ParameterTypeDescription
$aliasesarrayList of path aliases to be defined. The array keys are alias names (must start with @) and the array values are the corresponding paths or aliases. For example, [ ‘@models’ => ‘@app/models’, // an existing alias ‘@backend’ => DIR . ’/../backend’, // a directory ]

Returns

mixed

public function setBasePath(string $path): mixed

Sets the root directory of the module.

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

Parameters

ParameterTypeDescription
$pathstringThe root directory of the module. This can be either a directory name or a path alias.

Returns

mixed

Throws

public function setControllerPath(string $path): mixed

Sets the directory that contains the controller classes.

Parameters

ParameterTypeDescription
$pathstringThe root directory that contains the controller classes.

Returns

mixed

Throws

Since

2.0.44

public static function setInstance(yii\base\Module|null $instance): mixed

Sets the currently requested instance of this module class.

Parameters

ParameterTypeDescription
$instanceModule|nullThe currently requested instance of this module class. If it is null, the instance of the calling class will be removed, if any.

Returns

mixed

public function setLayoutPath(string $path): mixed

Sets the directory that contains the layout files.

Parameters

ParameterTypeDescription
$pathstringThe root directory or path alias of layout files.

Returns

mixed

Throws

public function setModule(string $id, yii\base\Module|array|null $module): mixed

Adds a sub-module to this module.

Parameters

ParameterTypeDescription
$idstringModule ID.
$moduleModule|array|nullThe sub-module to be added to this module. This can be one of the following: - a Module object - a configuration array: when getModule() is called initially, the array will be used to instantiate the sub-module - null: the named sub-module will be removed from this module

Returns

mixed

public function setModules(array $modules): mixed

Registers sub-modules in the current module.

Each sub-module should be specified as a name-value pair, where name refers to the ID of the module and value the module or a configuration array that can be used to create the module. In the latter case, Yii::createObject() will be used to create the module.

If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.

The following is an example for registering two sub-modules:

[
'comment' => [
'class' => 'app\modules\comment\CommentModule',
'db' => 'db',
],
'booking' => ['class' => 'app\modules\booking\BookingModule'],
]

Parameters

ParameterTypeDescription
$modulesarrayModules (id => module configuration or instances).

Returns

mixed

public function setVersion(string|callable|null $version): mixed

Sets current module version.

Parameters

ParameterTypeDescription
$versionstring|callable|nullThe version of this module. Version can be specified as a PHP callback, which can accept module instance as an argument and should return the actual version. For example: function (Module $module) { //return string }

Returns

mixed

Since

2.0.11

public function setViewPath(string $path): mixed

Sets the directory that contains the view files.

Parameters

ParameterTypeDescription
$pathstringThe root directory of view files.

Returns

mixed

Throws

protected function createStandaloneAction(string $route): yii\base\Action|null

Resolves a route to a standalone Action class through convention-based discovery under $actionNamespace.

Recurses through registered sub-modules using their first-segment ID, matching the pattern of createController(). When the route does not match a sub-module, the last segment is converted to a CamelCased class name with an Action suffix, the preceding segments form a sub-namespace prefix, and the result is looked up under the owning module’s $actionNamespace.

The resolved class must extend Action and must NOT extend Controller; otherwise this method returns null and the caller falls through to the controller pipeline (or to InvalidRouteException).

Parameters

ParameterTypeDescription
$routestringThe route relative to this module.

Returns

Action|null: A resolved standalone action ready for dispatch, or null when no class matches.

Since

22.0

protected function defaultVersion(): string

Returns default module version.

Child class may override this method to provide more specific version detection.

Returns

string: The version of this module.

Since

2.0.11

protected function runMappedAction(string $id, array $params): mixed

Runs a standalone action registered in $actionMap.

The action is instantiated via Yii::createObject() with no positional constructor arguments, allowing the DI container to autowire typed dependencies declared on the action’s constructor. The dispatcher assigns Action::$id after construction and then delegates lifecycle to runStandaloneAction().

Parameters

ParameterTypeDescription
$idstringThe action ID present in $actionMap.
$paramsarrayThe parameters to be matched against the action’s run() signature.

Returns

mixed: The action result, or null if execution was canceled by a before-action listener.

Since

22.0

protected function runStandaloneAction(yii\base\Action $action, array $params): mixed

Runs a standalone Action instance through the standard module/action event lifecycle.

Module ancestors fire EVENT_BEFORE_ACTION outer-to-inner before execution and EVENT_AFTER_ACTION inner-to-outer afterwards, mirroring Controller::runAction(). The action itself also fires Controller::EVENT_BEFORE_ACTION and Controller::EVENT_AFTER_ACTION so behaviors attached via the action’s behaviors() (for example AccessControl or VerbFilter) participate in the lifecycle.

Setting ActionEvent::$isValid to false in any before-action listener cancels the action and returns null.

Parameters

ParameterTypeDescription
$actionActionThe action to run.
$paramsarrayThe parameters to be matched against the action’s run() signature.

Returns

mixed: The action result, or null if execution was canceled by a before-action listener.

Since

22.0