W3cubDocs

/Yii 2.0

Class yii\base\Module

Inheritance yii\base\Module » yii\di\ServiceLocator » yii\base\Component » yii\base\Object
Implements yii\base\Configurable
Subclasses yii\base\Application, yii\console\Application, yii\debug\Module, yii\gii\Module, yii\web\Application
Available since version 2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/base/Module.php

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.

Public Properties

Property Type Description Defined By
$aliases array List of path aliases to be defined. yii\base\Module
$basePath string The root directory of the module. yii\base\Module
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$components array The list of the component definitions or the loaded component instances (ID => definition or instance). yii\di\ServiceLocator
$controllerMap array Mapping from controller ID to controller configurations. yii\base\Module
$controllerNamespace string The namespace that controller classes are in. yii\base\Module
$controllerPath string The directory that contains the controller classes. yii\base\Module
$defaultRoute string The default route of this module. yii\base\Module
$id string An ID that uniquely identifies this module among other modules which have the same parent. yii\base\Module
$layout string|boolean The layout that should be applied for views within this module. yii\base\Module
$layoutPath string The root directory of layout files. yii\base\Module
$module yii\base\Module The parent module of this module. yii\base\Module
$modules array The modules (indexed by their IDs). yii\base\Module
$params array Custom module parameters (name => value). yii\base\Module
$uniqueId string The unique ID of the module. yii\base\Module
$version string The version of this module. yii\base\Module
$viewPath string The root directory of view files. yii\base\Module

Public Methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Module
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
afterAction() This method is invoked right after an action within this module is executed. yii\base\Module
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
beforeAction() This method is invoked right before an action within this module is executed. yii\base\Module
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\Object
clear() Removes the component from the locator. yii\di\ServiceLocator
createController() Creates a controller instance based on the given route. yii\base\Module
createControllerByID() Creates a controller based on the given controller ID. yii\base\Module
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
get() Returns the component instance with the specified ID. yii\di\ServiceLocator
getBasePath() Returns the root directory of the module. yii\base\Module
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\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. yii\base\Module
getInstance() Returns the currently requested instance of this module class. yii\base\Module
getLayoutPath() Returns the directory that contains layout view files for this module. yii\base\Module
getModule() Retrieves the child module of the specified ID. yii\base\Module
getModules() Returns the sub-modules in this module. yii\base\Module
getUniqueId() Returns an ID that uniquely identifies this module among all modules within the current application. yii\base\Module
getVersion() Returns current module version. yii\base\Module
getViewPath() Returns the directory that contains the view files for this module. yii\base\Module
has() Returns a value indicating whether the locator has the specified component definition or has instantiated the component. yii\di\ServiceLocator
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasModule() Checks whether the child module of the specified ID exists. yii\base\Module
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the module. yii\base\Module
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
runAction() Runs a controller action specified by a route. yii\base\Module
set() Registers a component definition with this locator. yii\di\ServiceLocator
setAliases() Defines path aliases. yii\base\Module
setBasePath() Sets the root directory of the module. yii\base\Module
setComponents() Registers a set of component definitions in this locator. yii\di\ServiceLocator
setInstance() Sets the currently requested instance of this module class. yii\base\Module
setLayoutPath() Sets the directory that contains the layout files. yii\base\Module
setModule() Adds a sub-module to this module. yii\base\Module
setModules() Registers sub-modules in the current module. yii\base\Module
setVersion() Sets current module version. yii\base\Module
setViewPath() Sets the directory that contains the view files. yii\base\Module
trigger() Triggers an event. yii\base\Component

Protected Methods

Method Description Defined By
defaultVersion() Returns default module version. yii\base\Module

Events

Event Type Description Defined By
EVENT_AFTER_ACTION yii\base\ActionEvent An event raised after executing a controller action. yii\base\Module
EVENT_BEFORE_ACTION yii\base\ActionEvent An event raised before executing a controller action. yii\base\Module

Property Details

$aliases public write-only property

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
]
public void setAliases ( $aliases )

$basePath public property

The root directory of the module.

public string getBasePath ( )
public void setBasePath ( $path )

$controllerMap public property

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 array $controllerMap = []

$controllerNamespace public property

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 $controllerNamespace = null

$controllerPath public read-only property

The directory that contains the controller classes.

public string getControllerPath ( )

$defaultRoute public property

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 yii\base\Controller::$defaultAction.

public string $defaultRoute = 'default'

$id public property

An ID that uniquely identifies this module among other modules which have the same parent.

public string $id = null

$layout public property

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|boolean $layout = null

$layoutPath public property

The root directory of layout files. Defaults to "$viewPath/layouts".

public string getLayoutPath ( )
public void setLayoutPath ( $path )

$module public property

The parent module of this module. null if this module does not have a parent.

public yii\base\Module $module = null

$modules public property

The modules (indexed by their IDs).

public array getModules ( $loadedOnly = false )
public void setModules ( $modules )

$params public property

Custom module parameters (name => value).

public array $params = []

$uniqueId public read-only property

The unique ID of the module.

public string getUniqueId ( )

$version public property

The version of this module.

public string getVersion ( )
public void setVersion ( $version )

$viewPath public property

The root directory of view files. Defaults to "$basePath/views".

public string getViewPath ( )
public void setViewPath ( $path )

Method Details

__construct() public method

Constructor.

public void __construct ( $id, $parent = null, $config = [] )
$id string

The ID of this module.

$parent yii\base\Module

The parent module (if any).

$config array

Name-value pairs that will be used to initialize the object properties.

afterAction() public method

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;
}
public mixed afterAction ( $action, $result )
$action yii\base\Action

The action just executed.

$result mixed

The action return result.

return mixed

The processed action result.

beforeAction() public method

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
}
public boolean beforeAction ( $action )
$action yii\base\Action

The action to be executed.

return boolean

Whether the action should continue to be executed.

createController() public method

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 a valid module ID as declared in $modules, call the module's createController() with the rest part of the route;
  3. If the first segment of the route is found in $controllerMap, create a controller based on the corresponding configuration found in $controllerMap;
  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.

public array|boolean createController ( $route )
$route string

The route consisting of module, controller and action IDs.

return array|boolean

If the controller is created successfully, it will be returned together with the requested action ID. Otherwise false will be returned.

throws yii\base\InvalidConfigException

if the controller class and its file do not match.

createControllerByID() public method

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.

public yii\base\Controller|null createControllerByID ( $id )
$id string

The controller ID.

return yii\base\Controller|null

The newly created controller instance, or null if the controller ID is invalid.

throws yii\base\InvalidConfigException

if the controller class and its file name do not match. This exception is only thrown when in debug mode.

defaultVersion() protected method (available since version 2.0.11)

Returns default module version.

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

protected string defaultVersion ( )
return string

The version of this module.

getBasePath() public method

Returns the root directory of the module.

It defaults to the directory containing the module class file.

public string getBasePath ( )
return string

The root directory of the module.

getControllerPath() public method

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.

public string getControllerPath ( )
return string

The directory that contains the controller classes.

throws yii\base\InvalidParamException

if there is no alias defined for the root namespace of $controllerNamespace.

getInstance() public static method

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.

public static static|null getInstance ( )
return static|null

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

getLayoutPath() public method

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

public string getLayoutPath ( )
return string

The root directory of layout files. Defaults to "$viewPath/layouts".

getModule() public method

Retrieves the child module of the specified ID.

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

See also hasModule().

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

Module ID (case-sensitive). To retrieve grand child modules, use ID path relative to this module (e.g. admin/content).

$load boolean

Whether to load the module if it is not yet loaded.

return yii\base\Module|null

The module instance, null if the module does not exist.

getModules() public method

Returns the sub-modules in this module.

public array getModules ( $loadedOnly = false )
$loadedOnly boolean

Whether 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.

return array

The modules (indexed by their IDs).

getUniqueId() public method

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.

public string getUniqueId ( )
return string

The unique ID of the module.

getVersion() public method (available since version 2.0.11)

Returns current module version.

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

public string getVersion ( )
return string

The version of this module.

getViewPath() public method

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

public string getViewPath ( )
return string

The root directory of view files. Defaults to "$basePath/views".

hasModule() public method

Checks whether the child module of the specified ID exists.

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

public boolean hasModule ( $id )
$id string

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

return boolean

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

init() public method

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.

public void init ( )

runAction() public method

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 yii\base\Controller::runAction() to run the action with the given parameters. If the route is empty, the method will use $defaultRoute.

public mixed runAction ( $route, $params = [] )
$route string

The route that specifies the action.

$params array

The parameters to be passed to the action

return mixed

The result of the action.

throws yii\base\InvalidRouteException

if the requested route cannot be resolved into an action successfully.

setAliases() public method

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.

public void setAliases ( $aliases )
$aliases array

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
]

setBasePath() public method

Sets the root directory of the module.

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

public void setBasePath ( $path )
$path string

The root directory of the module. This can be either a directory name or a path alias.

throws yii\base\InvalidParamException

if the directory does not exist.

setInstance() public static method

Sets the currently requested instance of this module class.

public static void setInstance ( $instance )
$instance yii\base\Module|null

The currently requested instance of this module class. If it is null, the instance of the calling class will be removed, if any.

setLayoutPath() public method

Sets the directory that contains the layout files.

public void setLayoutPath ( $path )
$path string

The root directory or path alias of layout files.

throws yii\base\InvalidParamException

if the directory is invalid

setModule() public method

Adds a sub-module to this module.

public void setModule ( $id, $module )
$id string

Module ID.

$module yii\base\Module|array|null

The sub-module to be added to this module. This can be one of the following:

  • a yii\base\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

setModules() public method

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'],
]
public void setModules ( $modules )
$modules array

Modules (id => module configuration or instances).

setVersion() public method (available since version 2.0.11)

Sets current module version.

public void setVersion ( $version )
$version string|callable

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
}

setViewPath() public method

Sets the directory that contains the view files.

public void setViewPath ( $path )
$path string

The root directory of view files.

throws yii\base\InvalidParamException

if the directory is invalid.

Event Details

EVENT_AFTER_ACTION event of type yii\base\ActionEvent

An event raised after executing a controller action.

EVENT_BEFORE_ACTION event of type yii\base\ActionEvent

An event raised before executing a controller action. You may set yii\base\ActionEvent::$isValid to be false to cancel the action execution.

© 2008–2017 by Yii Software LLC
Licensed under the three clause BSD license.
http://www.yiiframework.com/doc-2.0/yii-base-module.html