3 * @link http://www.yiiframework.com/
4 * @copyright Copyright (c) 2008 Yii Software LLC
5 * @license http://www.yiiframework.com/license/
11 use yii\di\ServiceLocator;
14 * Module is the base class for module and application classes.
16 * A module represents a sub-application which contains MVC elements by itself, such as
17 * models, views, controllers, etc.
19 * A module may consist of [[modules|sub-modules]].
21 * [[components|Components]] may be registered with the module so that they are globally
22 * accessible within the module.
24 * For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
26 * @property-write array $aliases List of path aliases to be defined. The array keys are alias names (must
27 * start with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an
28 * example. This property is write-only.
29 * @property string $basePath The root directory of the module.
30 * @property-read string $controllerPath The directory that contains the controller classes. This property is
32 * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
33 * @property array $modules The modules (indexed by their IDs).
34 * @property-read string $uniqueId The unique ID of the module. This property is read-only.
35 * @property string $version The version of this module. Note that the type of this property differs in getter
36 * and setter. See [[getVersion()]] and [[setVersion()]] for details.
37 * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
39 * @author Qiang Xue <qiang.xue@gmail.com>
42 class Module extends ServiceLocator
45 * @event ActionEvent an event raised before executing a controller action.
46 * You may set [[ActionEvent::isValid]] to be `false` to cancel the action execution.
48 const EVENT_BEFORE_ACTION = 'beforeAction';
50 * @event ActionEvent an event raised after executing a controller action.
52 const EVENT_AFTER_ACTION = 'afterAction';
55 * @var array custom module parameters (name => value).
59 * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
63 * @var Module the parent module of this module. `null` if this module does not have a parent.
67 * @var string|bool the layout that should be applied for views within this module. This refers to a view name
68 * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
69 * will be taken. If this is `false`, layout will be disabled within this module.
73 * @var array mapping from controller ID to controller configurations.
74 * Each name-value pair specifies the configuration of a single controller.
75 * A controller configuration can be either a string or an array.
76 * If the former, the string should be the fully qualified class name of the controller.
77 * If the latter, the array must contain a `class` element which specifies
78 * the controller's fully qualified class name, and the rest of the name-value pairs
79 * in the array are used to initialize the corresponding controller properties. For example,
83 * 'account' => 'app\controllers\UserController',
85 * 'class' => 'app\controllers\PostController',
86 * 'pageTitle' => 'something new',
91 public $controllerMap = [];
93 * @var string the namespace that controller classes are in.
94 * This namespace will be used to load controller classes by prepending it to the controller
97 * If not set, it will use the `controllers` sub-namespace under the namespace of this module.
98 * For example, if the namespace of this module is `foo\bar`, then the default
99 * controller namespace would be `foo\bar\controllers`.
101 * See also the [guide section on autoloading](guide:concept-autoloading) to learn more about
102 * defining namespaces and how classes are loaded.
104 public $controllerNamespace;
106 * @var string the default route of this module. Defaults to `default`.
107 * The route may consist of child module ID, controller ID, and/or action ID.
108 * For example, `help`, `post/create`, `admin/post/create`.
109 * If action ID is not given, it will take the default value as specified in
110 * [[Controller::defaultAction]].
112 public $defaultRoute = 'default';
115 * @var string the root directory of the module.
119 * @var string the root directory that contains view files for this module
123 * @var string the root directory that contains layout view files for this module.
125 private $_layoutPath;
127 * @var array child modules of this module
129 private $_modules = [];
131 * @var string|callable the version of this module.
132 * Version can be specified as a PHP callback, which can accept module instance as an argument and should
133 * return the actual version. For example:
136 * function (Module $module) {
137 * //return string|int
141 * If not set, [[defaultVersion()]] will be used to determine actual value.
150 * @param string $id the ID of this module.
151 * @param Module $parent the parent module (if any).
152 * @param array $config name-value pairs that will be used to initialize the object properties.
154 public function __construct($id, $parent = null, $config = [])
157 $this->module = $parent;
158 parent::__construct($config);
162 * Returns the currently requested instance of this module class.
163 * If the module class is not currently requested, `null` will be returned.
164 * This method is provided so that you access the module instance from anywhere within the module.
165 * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
167 public static function getInstance()
169 $class = get_called_class();
170 return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
174 * Sets the currently requested instance of this module class.
175 * @param Module|null $instance the currently requested instance of this module class.
176 * If it is `null`, the instance of the calling class will be removed, if any.
178 public static function setInstance($instance)
180 if ($instance === null) {
181 unset(Yii::$app->loadedModules[get_called_class()]);
183 Yii::$app->loadedModules[get_class($instance)] = $instance;
188 * Initializes the module.
190 * This method is called after the module is created and initialized with property values
191 * given in configuration. The default implementation will initialize [[controllerNamespace]]
194 * If you override this method, please make sure you call the parent implementation.
196 public function init()
198 if ($this->controllerNamespace === null) {
199 $class = get_class($this);
200 if (($pos = strrpos($class, '\\')) !== false) {
201 $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
207 * Returns an ID that uniquely identifies this module among all modules within the current application.
208 * Note that if the module is an application, an empty string will be returned.
209 * @return string the unique ID of the module.
211 public function getUniqueId()
213 return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
217 * Returns the root directory of the module.
218 * It defaults to the directory containing the module class file.
219 * @return string the root directory of the module.
221 public function getBasePath()
223 if ($this->_basePath === null) {
224 $class = new \ReflectionClass($this);
225 $this->_basePath = dirname($class->getFileName());
228 return $this->_basePath;
232 * Sets the root directory of the module.
233 * This method can only be invoked at the beginning of the constructor.
234 * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
235 * @throws InvalidArgumentException if the directory does not exist.
237 public function setBasePath($path)
239 $path = Yii::getAlias($path);
240 $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
241 if ($p !== false && is_dir($p)) {
242 $this->_basePath = $p;
244 throw new InvalidArgumentException("The directory does not exist: $path");
249 * Returns the directory that contains the controller classes according to [[controllerNamespace]].
250 * Note that in order for this method to return a value, you must define
251 * an alias for the root namespace of [[controllerNamespace]].
252 * @return string the directory that contains the controller classes.
253 * @throws InvalidArgumentException if there is no alias defined for the root namespace of [[controllerNamespace]].
255 public function getControllerPath()
257 return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
261 * Returns the directory that contains the view files for this module.
262 * @return string the root directory of view files. Defaults to "[[basePath]]/views".
264 public function getViewPath()
266 if ($this->_viewPath === null) {
267 $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
270 return $this->_viewPath;
274 * Sets the directory that contains the view files.
275 * @param string $path the root directory of view files.
276 * @throws InvalidArgumentException if the directory is invalid.
278 public function setViewPath($path)
280 $this->_viewPath = Yii::getAlias($path);
284 * Returns the directory that contains layout view files for this module.
285 * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
287 public function getLayoutPath()
289 if ($this->_layoutPath === null) {
290 $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
293 return $this->_layoutPath;
297 * Sets the directory that contains the layout files.
298 * @param string $path the root directory or [path alias](guide:concept-aliases) of layout files.
299 * @throws InvalidArgumentException if the directory is invalid
301 public function setLayoutPath($path)
303 $this->_layoutPath = Yii::getAlias($path);
307 * Returns current module version.
308 * If version is not explicitly set, [[defaultVersion()]] method will be used to determine its value.
309 * @return string the version of this module.
312 public function getVersion()
314 if ($this->_version === null) {
315 $this->_version = $this->defaultVersion();
317 if (!is_scalar($this->_version)) {
318 $this->_version = call_user_func($this->_version, $this);
322 return $this->_version;
326 * Sets current module version.
327 * @param string|callable $version the version of this module.
328 * Version can be specified as a PHP callback, which can accept module instance as an argument and should
329 * return the actual version. For example:
332 * function (Module $module) {
339 public function setVersion($version)
341 $this->_version = $version;
345 * Returns default module version.
346 * Child class may override this method to provide more specific version detection.
347 * @return string the version of this module.
350 protected function defaultVersion()
352 if ($this->module === null) {
356 return $this->module->getVersion();
360 * Defines path aliases.
361 * This method calls [[Yii::setAlias()]] to register the path aliases.
362 * This method is provided so that you can define path aliases when configuring a module.
363 * @property array list of path aliases to be defined. The array keys are alias names
364 * (must start with `@`) and the array values are the corresponding paths or aliases.
365 * See [[setAliases()]] for an example.
366 * @param array $aliases list of path aliases to be defined. The array keys are alias names
367 * (must start with `@`) and the array values are the corresponding paths or aliases.
372 * '@models' => '@app/models', // an existing alias
373 * '@backend' => __DIR__ . '/../backend', // a directory
377 public function setAliases($aliases)
379 foreach ($aliases as $name => $alias) {
380 Yii::setAlias($name, $alias);
385 * Checks whether the child module of the specified ID exists.
386 * This method supports checking the existence of both child and grand child modules.
387 * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
388 * @return bool whether the named module exists. Both loaded and unloaded modules
391 public function hasModule($id)
393 if (($pos = strpos($id, '/')) !== false) {
395 $module = $this->getModule(substr($id, 0, $pos));
397 return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
400 return isset($this->_modules[$id]);
404 * Retrieves the child module of the specified ID.
405 * This method supports retrieving both child modules and grand child modules.
406 * @param string $id module ID (case-sensitive). To retrieve grand child modules,
407 * use ID path relative to this module (e.g. `admin/content`).
408 * @param bool $load whether to load the module if it is not yet loaded.
409 * @return Module|null the module instance, `null` if the module does not exist.
412 public function getModule($id, $load = true)
414 if (($pos = strpos($id, '/')) !== false) {
416 $module = $this->getModule(substr($id, 0, $pos));
418 return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
421 if (isset($this->_modules[$id])) {
422 if ($this->_modules[$id] instanceof self) {
423 return $this->_modules[$id];
425 Yii::debug("Loading module: $id", __METHOD__);
426 /* @var $module Module */
427 $module = Yii::createObject($this->_modules[$id], [$id, $this]);
428 $module::setInstance($module);
429 return $this->_modules[$id] = $module;
437 * Adds a sub-module to this module.
438 * @param string $id module ID.
439 * @param Module|array|null $module the sub-module to be added to this module. This can
440 * be one of the following:
442 * - a [[Module]] object
443 * - a configuration array: when [[getModule()]] is called initially, the array
444 * will be used to instantiate the sub-module
445 * - `null`: the named sub-module will be removed from this module
447 public function setModule($id, $module)
449 if ($module === null) {
450 unset($this->_modules[$id]);
452 $this->_modules[$id] = $module;
453 if ($module instanceof self) {
454 $module->module = $this;
460 * Returns the sub-modules in this module.
461 * @param bool $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
462 * then all sub-modules registered in this module will be returned, whether they are loaded or not.
463 * Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
464 * @return array the modules (indexed by their IDs).
466 public function getModules($loadedOnly = false)
470 foreach ($this->_modules as $module) {
471 if ($module instanceof self) {
472 $modules[] = $module;
479 return $this->_modules;
483 * Registers sub-modules in the current module.
485 * Each sub-module should be specified as a name-value pair, where
486 * name refers to the ID of the module and value the module or a configuration
487 * array that can be used to create the module. In the latter case, [[Yii::createObject()]]
488 * will be used to create the module.
490 * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
492 * The following is an example for registering two sub-modules:
497 * 'class' => 'app\modules\comment\CommentModule',
500 * 'booking' => ['class' => 'app\modules\booking\BookingModule'],
504 * @param array $modules modules (id => module configuration or instances).
506 public function setModules($modules)
508 foreach ($modules as $id => $module) {
509 $this->_modules[$id] = $module;
510 if ($module instanceof self) {
511 $module->module = $this;
517 * Runs a controller action specified by a route.
518 * This method parses the specified route and creates the corresponding child module(s), controller and action
519 * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
520 * If the route is empty, the method will use [[defaultRoute]].
521 * @param string $route the route that specifies the action.
522 * @param array $params the parameters to be passed to the action
523 * @return mixed the result of the action.
524 * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully.
526 public function runAction($route, $params = [])
528 $parts = $this->createController($route);
529 if (is_array($parts)) {
530 /* @var $controller Controller */
531 list($controller, $actionID) = $parts;
532 $oldController = Yii::$app->controller;
533 Yii::$app->controller = $controller;
534 $result = $controller->runAction($actionID, $params);
535 if ($oldController !== null) {
536 Yii::$app->controller = $oldController;
542 $id = $this->getUniqueId();
543 throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
547 * Creates a controller instance based on the given route.
549 * The route should be relative to this module. The method implements the following algorithm
550 * to resolve the given route:
552 * 1. If the route is empty, use [[defaultRoute]];
553 * 2. If the first segment of the route is found in [[controllerMap]], create a controller
554 * based on the corresponding configuration found in [[controllerMap]];
555 * 3. If the first segment of the route is a valid module ID as declared in [[modules]],
556 * call the module's `createController()` with the rest part of the route;
557 * 4. The given route is in the format of `abc/def/xyz`. Try either `abc\DefController`
558 * or `abc\def\XyzController` class within the [[controllerNamespace|controller namespace]].
560 * If any of the above steps resolves into a controller, it is returned together with the rest
561 * part of the route which will be treated as the action ID. Otherwise, `false` will be returned.
563 * @param string $route the route consisting of module, controller and action IDs.
564 * @return array|bool If the controller is created successfully, it will be returned together
565 * with the requested action ID. Otherwise `false` will be returned.
566 * @throws InvalidConfigException if the controller class and its file do not match.
568 public function createController($route)
571 $route = $this->defaultRoute;
574 // double slashes or leading/ending slashes may cause substr problem
575 $route = trim($route, '/');
576 if (strpos($route, '//') !== false) {
580 if (strpos($route, '/') !== false) {
581 list($id, $route) = explode('/', $route, 2);
587 // module and controller map take precedence
588 if (isset($this->controllerMap[$id])) {
589 $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
590 return [$controller, $route];
592 $module = $this->getModule($id);
593 if ($module !== null) {
594 return $module->createController($route);
597 if (($pos = strrpos($route, '/')) !== false) {
598 $id .= '/' . substr($route, 0, $pos);
599 $route = substr($route, $pos + 1);
602 $controller = $this->createControllerByID($id);
603 if ($controller === null && $route !== '') {
604 $controller = $this->createControllerByID($id . '/' . $route);
608 return $controller === null ? false : [$controller, $route];
612 * Creates a controller based on the given controller ID.
614 * The controller ID is relative to this module. The controller class
615 * should be namespaced under [[controllerNamespace]].
617 * Note that this method does not check [[modules]] or [[controllerMap]].
619 * @param string $id the controller ID.
620 * @return Controller|null the newly created controller instance, or `null` if the controller ID is invalid.
621 * @throws InvalidConfigException if the controller class and its file name do not match.
622 * This exception is only thrown when in debug mode.
624 public function createControllerByID($id)
626 $pos = strrpos($id, '/');
627 if ($pos === false) {
631 $prefix = substr($id, 0, $pos + 1);
632 $className = substr($id, $pos + 1);
635 if ($this->isIncorrectClassNameOrPrefix($className, $prefix)) {
639 $className = preg_replace_callback('%-([a-z0-9_])%i', function ($matches) {
640 return ucfirst($matches[1]);
641 }, ucfirst($className)) . 'Controller';
642 $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
643 if (strpos($className, '-') !== false || !class_exists($className)) {
647 if (is_subclass_of($className, 'yii\base\Controller')) {
648 $controller = Yii::createObject($className, [$id, $this]);
649 return get_class($controller) === $className ? $controller : null;
650 } elseif (YII_DEBUG) {
651 throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
658 * Checks if class name or prefix is incorrect
660 * @param string $className
661 * @param string $prefix
664 private function isIncorrectClassNameOrPrefix($className, $prefix)
666 if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
669 if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
677 * This method is invoked right before an action within this module is executed.
679 * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
680 * will determine whether the action should continue to run.
682 * In case the action should not run, the request should be handled inside of the `beforeAction` code
683 * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
685 * If you override this method, your code should look like the following:
688 * public function beforeAction($action)
690 * if (!parent::beforeAction($action)) {
694 * // your custom code here
696 * return true; // or false to not run the action
700 * @param Action $action the action to be executed.
701 * @return bool whether the action should continue to be executed.
703 public function beforeAction($action)
705 $event = new ActionEvent($action);
706 $this->trigger(self::EVENT_BEFORE_ACTION, $event);
707 return $event->isValid;
711 * This method is invoked right after an action within this module is executed.
713 * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
714 * will be used as the action return value.
716 * If you override this method, your code should look like the following:
719 * public function afterAction($action, $result)
721 * $result = parent::afterAction($action, $result);
722 * // your custom code here
727 * @param Action $action the action just executed.
728 * @param mixed $result the action return result.
729 * @return mixed the processed action result.
731 public function afterAction($action, $result)
733 $event = new ActionEvent($action);
734 $event->result = $result;
735 $this->trigger(self::EVENT_AFTER_ACTION, $event);
736 return $event->result;
742 * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
743 * The parent module may be the application.
745 public function get($id, $throwException = true)
747 if (!isset($this->module)) {
748 return parent::get($id, $throwException);
751 $component = parent::get($id, false);
752 if ($component === null) {
753 $component = $this->module->get($id, $throwException);
761 * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
762 * The parent module may be the application.
764 public function has($id, $checkInstance = false)
766 return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));