Module.php 23.8 KB
Newer Older
resurtm committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

use Yii;

/**
 * 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 [[modules|sub-modules]].
 *
 * [[components|Components]] may be registered with the module so that they are globally
 * accessible within the module.
 *
23 24 25 26 27
 * @property 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. See [[setAliases()]] for an example.
 * This property is write-only.
 * @property string $basePath The root directory of the module.
 * @property array $components The components (indexed by their IDs).
28 29
 * @property string $controllerPath The directory that contains the controller classes according to [[controllerNamespace]].
 * This property is read-only.
30 31 32 33
 * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
 * @property array $modules The modules (indexed by their IDs).
 * @property string $uniqueId The unique ID of the module. This property is read-only.
 * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/view".
resurtm committed
34 35 36 37
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
38
class Module extends Component
resurtm committed
39 40 41 42
{
	/**
	 * @var array custom module parameters (name => value).
	 */
Alexander Makarov committed
43
	public $params = [];
resurtm committed
44
	/**
45
	 * @var array the IDs of the components or modules that should be preloaded right after initialization.
resurtm committed
46
	 */
Alexander Makarov committed
47
	public $preload = [];
resurtm committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	/**
	 * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
	 */
	public $id;
	/**
	 * @var Module the parent module of this module. Null if this module does not have a parent.
	 */
	public $module;
	/**
	 * @var string|boolean 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 [[module|parent module]]
	 * will be taken. If this is false, layout will be disabled within this module.
	 */
	public $layout;
	/**
	 * @var array 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.
66
	 * If the former, the string should be the fully qualified class name of the controller.
resurtm committed
67
	 * If the latter, the array must contain a 'class' element which specifies
68
	 * the controller's fully qualified class name, and the rest of the name-value pairs
resurtm committed
69 70 71
	 * in the array are used to initialize the corresponding controller properties. For example,
	 *
	 * ~~~
Alexander Makarov committed
72
	 * [
73
	 *   'account' => 'app\controllers\UserController',
Alexander Makarov committed
74
	 *   'article' => [
75
	 *      'class' => 'app\controllers\PostController',
resurtm committed
76
	 *      'pageTitle' => 'something new',
Alexander Makarov committed
77 78
	 *   ],
	 * ]
resurtm committed
79 80
	 * ~~~
	 */
Alexander Makarov committed
81
	public $controllerMap = [];
resurtm committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	/**
	 * @var string the namespace that controller classes are in. 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".
	 */
	public $controllerNamespace;
	/**
	 * @return string 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 $defaultRoute = 'default';
	/**
	 * @var string the root directory of the module.
	 */
	private $_basePath;
	/**
	 * @var string the root directory that contains view files for this module
	 */
	private $_viewPath;
	/**
	 * @var string the root directory that contains layout view files for this module.
	 */
	private $_layoutPath;
	/**
	 * @var array child modules of this module
	 */
Alexander Makarov committed
112
	private $_modules = [];
resurtm committed
113 114 115
	/**
	 * @var array components registered under this module
	 */
Alexander Makarov committed
116
	private $_components = [];
resurtm committed
117 118 119 120 121 122 123

	/**
	 * Constructor.
	 * @param string $id the ID of this module
	 * @param Module $parent the parent module (if any)
	 * @param array $config name-value pairs that will be used to initialize the object properties
	 */
Alexander Makarov committed
124
	public function __construct($id, $parent = null, $config = [])
resurtm committed
125 126 127
	{
		$this->id = $id;
		$this->module = $parent;
128
		parent::__construct($config);
resurtm committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
	}

	/**
	 * Getter magic method.
	 * This method is overridden to support accessing components
	 * like reading module properties.
	 * @param string $name component or property name
	 * @return mixed the named property value
	 */
	public function __get($name)
	{
		if ($this->hasComponent($name)) {
			return $this->getComponent($name);
		} else {
			return parent::__get($name);
		}
	}

	/**
	 * Checks if a property value is null.
	 * This method overrides the parent implementation by checking
	 * if the named component is loaded.
	 * @param string $name the property name or the event name
	 * @return boolean whether the property value is null
	 */
	public function __isset($name)
	{
		if ($this->hasComponent($name)) {
			return $this->getComponent($name) !== null;
		} else {
			return parent::__isset($name);
		}
	}

	/**
	 * Initializes the module.
	 * This method is called after the module is created and initialized with property values
Qiang Xue committed
166 167
	 * given in configuration. The default implementation will call [[preloadComponents()]] to
	 * load components that are declared in [[preload]].
168 169
	 *
	 * If you override this method, please make sure you call the parent implementation.
resurtm committed
170 171 172
	 */
	public function init()
	{
173 174 175 176 177 178
		if ($this->controllerNamespace === null) {
			$class = get_class($this);
			if (($pos = strrpos($class, '\\')) !== false) {
				$this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
			}
		}
179
		$this->preloadComponents();
resurtm committed
180 181 182 183 184 185 186 187 188
	}

	/**
	 * 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.
	 * @return string the unique ID of the module.
	 */
	public function getUniqueId()
	{
Qiang Xue committed
189
		return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
resurtm committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	}

	/**
	 * Returns the root directory of the module.
	 * It defaults to the directory containing the module class file.
	 * @return string the root directory of the module.
	 */
	public function getBasePath()
	{
		if ($this->_basePath === null) {
			$class = new \ReflectionClass($this);
			$this->_basePath = dirname($class->getFileName());
		}
		return $this->_basePath;
	}

	/**
	 * Sets the root directory of the module.
	 * This method can only be invoked at the beginning of the constructor.
	 * @param string $path the root directory of the module. This can be either a directory name or a path alias.
	 * @throws InvalidParamException if the directory does not exist.
	 */
	public function setBasePath($path)
	{
		$path = Yii::getAlias($path);
		$p = realpath($path);
		if ($p !== false && is_dir($p)) {
			$this->_basePath = $p;
		} else {
			throw new InvalidParamException("The directory does not exist: $path");
		}
	}

	/**
224
	 * Returns the directory that contains the controller classes according to [[controllerNamespace]].
225 226
	 * Note that in order for this method to return a value, you must define
	 * an alias for the root namespace of [[controllerNamespace]].
resurtm committed
227
	 * @return string the directory that contains the controller classes.
228
	 * @throws InvalidParamException if there is no alias defined for the root namespace of [[controllerNamespace]].
resurtm committed
229 230 231
	 */
	public function getControllerPath()
	{
232
		return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
resurtm committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	}

	/**
	 * Returns the directory that contains the view files for this module.
	 * @return string the root directory of view files. Defaults to "[[basePath]]/view".
	 */
	public function getViewPath()
	{
		if ($this->_viewPath !== null) {
			return $this->_viewPath;
		} else {
			return $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
		}
	}

	/**
	 * Sets the directory that contains the view files.
	 * @param string $path the root directory of view files.
251
	 * @throws InvalidParamException if the directory is invalid
resurtm committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
	 */
	public function setViewPath($path)
	{
		$this->_viewPath = Yii::getAlias($path);
	}

	/**
	 * Returns the directory that contains layout view files for this module.
	 * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
	 */
	public function getLayoutPath()
	{
		if ($this->_layoutPath !== null) {
			return $this->_layoutPath;
		} else {
			return $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
		}
	}

	/**
	 * Sets the directory that contains the layout files.
	 * @param string $path the root directory of layout files.
274
	 * @throws InvalidParamException if the directory is invalid
resurtm committed
275 276 277 278 279 280 281 282 283 284
	 */
	public function setLayoutPath($path)
	{
		$this->_layoutPath = Yii::getAlias($path);
	}

	/**
	 * 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.
285 286 287
	 * @property 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.
	 * See [[setAliases()]] for an example.
resurtm committed
288 289 290 291 292
	 * @param 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,
	 *
	 * ~~~
Alexander Makarov committed
293
	 * [
resurtm committed
294 295
	 *	'@models' => '@app/models', // an existing alias
	 *	'@backend' => __DIR__ . '/../backend',  // a directory
Alexander Makarov committed
296
	 * ]
resurtm committed
297 298 299 300 301 302 303 304 305 306
	 * ~~~
	 */
	public function setAliases($aliases)
	{
		foreach ($aliases as $name => $alias) {
			Yii::setAlias($name, $alias);
		}
	}

	/**
307 308 309
	 * Checks whether the child module of the specified ID exists.
	 * This method supports checking the existence of both child and grand child modules.
	 * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
resurtm committed
310 311 312 313 314
	 * @return boolean whether the named module exists. Both loaded and unloaded modules
	 * are considered.
	 */
	public function hasModule($id)
	{
315 316 317 318
		if (($pos = strpos($id, '/')) !== false) {
			// sub-module
			$module = $this->getModule(substr($id, 0, $pos));
			return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
319
		} else {
320
			return isset($this->_modules[$id]);
321
		}
resurtm committed
322 323 324
	}

	/**
325 326 327 328
	 * Retrieves the child module of the specified ID.
	 * This method supports retrieving both child modules and grand child modules.
	 * @param string $id module ID (case-sensitive). To retrieve grand child modules,
	 * use ID path relative to this module (e.g. `admin/content`).
resurtm committed
329
	 * @param boolean $load whether to load the module if it is not yet loaded.
Qiang Xue committed
330
	 * @return Module|null the module instance, null if the module does not exist.
resurtm committed
331 332 333 334
	 * @see hasModule()
	 */
	public function getModule($id, $load = true)
	{
335 336 337 338 339 340 341 342 343 344 345
		if (($pos = strpos($id, '/')) !== false) {
			// sub-module
			$module = $this->getModule(substr($id, 0, $pos));
			return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
		}

		if (isset($this->_modules[$id])) {
			if ($this->_modules[$id] instanceof Module) {
				return $this->_modules[$id];
			} elseif ($load) {
				Yii::trace("Loading module: $id", __METHOD__);
346 347 348
				if (is_array($this->_modules[$id]) && !isset($this->_modules[$id]['class'])) {
					$this->_modules[$id]['class'] = 'yii\base\Module';
				}
349
				return $this->_modules[$id] = Yii::createObject($this->_modules[$id], $id, $this);
resurtm committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
			}
		}
		return null;
	}

	/**
	 * Adds a sub-module to this module.
	 * @param string $id module ID
	 * @param Module|array|null $module the sub-module to be added to this module. This can
	 * be one of the followings:
	 *
	 * - 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
	 */
	public function setModule($id, $module)
	{
		if ($module === null) {
			unset($this->_modules[$id]);
		} else {
			$this->_modules[$id] = $module;
		}
	}

	/**
	 * Returns the sub-modules in this module.
	 * @param boolean $loadedOnly 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)
	 */
	public function getModules($loadedOnly = false)
	{
		if ($loadedOnly) {
Alexander Makarov committed
385
			$modules = [];
resurtm committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
			foreach ($this->_modules as $module) {
				if ($module instanceof Module) {
					$modules[] = $module;
				}
			}
			return $modules;
		} else {
			return $this->_modules;
		}
	}

	/**
	 * 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:
	 *
	 * ~~~
Alexander Makarov committed
410 411
	 * [
	 *     'comment' => [
resurtm committed
412 413
	 *         'class' => 'app\modules\comment\CommentModule',
	 *         'db' => 'db',
Alexander Makarov committed
414 415 416
	 *     ],
	 *     'booking' => ['class' => 'app\modules\booking\BookingModule'],
	 * ]
resurtm committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	 * ~~~
	 *
	 * @param array $modules modules (id => module configuration or instances)
	 */
	public function setModules($modules)
	{
		foreach ($modules as $id => $module) {
			$this->_modules[$id] = $module;
		}
	}

	/**
	 * Checks whether the named component exists.
	 * @param string $id component ID
	 * @return boolean whether the named component exists. Both loaded and unloaded components
	 * are considered.
	 */
	public function hasComponent($id)
	{
		return isset($this->_components[$id]);
	}

	/**
	 * Retrieves the named component.
	 * @param string $id component ID (case-sensitive)
	 * @param boolean $load whether to load the component if it is not yet loaded.
	 * @return Component|null the component instance, null if the component does not exist.
	 * @see hasComponent()
	 */
	public function getComponent($id, $load = true)
	{
		if (isset($this->_components[$id])) {
			if ($this->_components[$id] instanceof Object) {
				return $this->_components[$id];
			} elseif ($load) {
				return $this->_components[$id] = Yii::createObject($this->_components[$id]);
			}
		}
		return null;
	}

	/**
	 * Registers a component with this module.
	 * @param string $id component ID
	 * @param Component|array|null $component the component to be registered with the module. This can
	 * be one of the followings:
	 *
	 * - a [[Component]] object
	 * - a configuration array: when [[getComponent()]] is called initially for this component, the array
	 *   will be used to instantiate the component via [[Yii::createObject()]].
	 * - null: the named component will be removed from the module
	 */
	public function setComponent($id, $component)
	{
		if ($component === null) {
			unset($this->_components[$id]);
		} else {
			$this->_components[$id] = $component;
		}
	}

	/**
	 * Returns the registered components.
	 * @param boolean $loadedOnly whether to return the loaded components only. If this is set false,
	 * then all components specified in the configuration will be returned, whether they are loaded or not.
	 * Loaded components will be returned as objects, while unloaded components as configuration arrays.
	 * @return array the components (indexed by their IDs)
	 */
	public function getComponents($loadedOnly = false)
	{
		if ($loadedOnly) {
Alexander Makarov committed
488
			$components = [];
resurtm committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
			foreach ($this->_components as $component) {
				if ($component instanceof Component) {
					$components[] = $component;
				}
			}
			return $components;
		} else {
			return $this->_components;
		}
	}

	/**
	 * Registers a set of components in this module.
	 *
	 * Each component should be specified as a name-value pair, where
	 * name refers to the ID of the component and value the component or a configuration
	 * array that can be used to create the component. In the latter case, [[Yii::createObject()]]
	 * will be used to create the component.
	 *
	 * If a new component has the same ID as an existing one, the existing one will be overwritten silently.
	 *
	 * The following is an example for setting two components:
	 *
	 * ~~~
Alexander Makarov committed
513 514
	 * [
	 *     'db' => [
resurtm committed
515 516
	 *         'class' => 'yii\db\Connection',
	 *         'dsn' => 'sqlite:path/to/file.db',
Alexander Makarov committed
517 518
	 *     ],
	 *     'cache' => [
resurtm committed
519 520
	 *         'class' => 'yii\caching\DbCache',
	 *         'db' => 'db',
Alexander Makarov committed
521 522
	 *     ],
	 * ]
resurtm committed
523 524 525 526 527 528 529
	 * ~~~
	 *
	 * @param array $components components (id => component configuration or instance)
	 */
	public function setComponents($components)
	{
		foreach ($components as $id => $component) {
Qiang Xue committed
530 531
			if (!is_object($component) && isset($this->_components[$id]['class']) && !isset($component['class'])) {
				// set default component class
532
				$component['class'] = $this->_components[$id]['class'];
resurtm committed
533
			}
534
			$this->_components[$id] = $component;
resurtm committed
535 536 537 538 539
		}
	}

	/**
	 * Loads components that are declared in [[preload]].
Qiang Xue committed
540
	 * @throws InvalidConfigException if a component or module to be preloaded is unknown
resurtm committed
541 542 543 544
	 */
	public function preloadComponents()
	{
		foreach ($this->preload as $id) {
Qiang Xue committed
545 546 547 548 549 550 551
			if ($this->hasComponent($id)) {
				$this->getComponent($id);
			} elseif ($this->hasModule($id)) {
				$this->getModule($id);
			} else {
				throw new InvalidConfigException("Unknown component or module: $id");
			}
resurtm committed
552 553 554 555 556 557 558 559 560 561
		}
	}

	/**
	 * 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]].
	 * @param string $route the route that specifies the action.
	 * @param array $params the parameters to be passed to the action
562
	 * @return mixed the result of the action.
resurtm committed
563 564
	 * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully
	 */
Alexander Makarov committed
565
	public function runAction($route, $params = [])
resurtm committed
566
	{
567 568
		$parts = $this->createController($route);
		if (is_array($parts)) {
slavcodev committed
569
			/** @var Controller $controller */
570
			list($controller, $actionID) = $parts;
resurtm committed
571 572
			$oldController = Yii::$app->controller;
			Yii::$app->controller = $controller;
573
			$result = $controller->runAction($actionID, $params);
resurtm committed
574
			Yii::$app->controller = $oldController;
575
			return $result;
resurtm committed
576
		} else {
577 578
			$id = $this->getUniqueId();
			throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
resurtm committed
579 580 581 582
		}
	}

	/**
583
	 * Creates a controller instance based on the given route.
resurtm committed
584
	 *
585 586 587 588 589 590 591 592 593 594 595 596 597
	 * 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 [[controllerNamespace|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.
resurtm committed
598 599 600 601 602 603 604 605 606 607 608
	 *
	 * @param string $route 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 InvalidConfigException if the controller class and its file do not match.
	 */
	public function createController($route)
	{
		if ($route === '') {
			$route = $this->defaultRoute;
		}
609 610 611 612 613 614 615

		// double slashes or leading/ending slashes may cause substr problem
		$route = trim($route, '/');
		if (strpos($route, '//') !== false) {
			return false;
		}

616 617
		if (strpos($route, '/') !== false) {
			list ($id, $route) = explode('/', $route, 2);
resurtm committed
618 619 620 621 622
		} else {
			$id = $route;
			$route = '';
		}

623
		// module and controller map take precedence
resurtm committed
624 625 626 627 628 629
		$module = $this->getModule($id);
		if ($module !== null) {
			return $module->createController($route);
		}
		if (isset($this->controllerMap[$id])) {
			$controller = Yii::createObject($this->controllerMap[$id], $id, $this);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
			return [$controller, $route];
		}

		if (($pos = strrpos($route, '/')) !== false) {
			$id .= '/' . substr($route, 0, $pos);
			$route = substr($route, $pos + 1);
		}

		$controller = $this->createControllerByID($id);
		if ($controller === null && $route !== '') {
			$controller = $this->createControllerByID($id . '/' . $route);
			$route = '';
		}

		return $controller === null ? false : [$controller, $route];
	}

	/**
	 * Creates a controller based on the given controller ID.
	 *
	 * The controller ID is relative to this module. The controller class
651
	 * should be namespaced under [[controllerNamespace]].
652 653 654 655 656 657 658 659 660 661 662 663
	 *
	 * Note that this method does not check [[modules]] or [[controllerMap]].
	 *
	 * @param string $id the controller ID
	 * @return Controller 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 createControllerByID($id)
	{
		if (!preg_match('%^[a-z0-9\\-_/]+$%', $id)) {
			return null;
resurtm committed
664 665
		}

666 667 668 669 670 671 672 673 674 675
		$pos = strrpos($id, '/');
		if ($pos === false) {
			$prefix = '';
			$className = $id;
		} else {
			$prefix = substr($id, 0, $pos + 1);
			$className = substr($id, $pos + 1);
		}

		$className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller';
676
		$className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix)  . $className, '\\');
677
		if (strpos($className, '-') !== false || !class_exists($className)) {
678 679 680 681 682 683 684 685 686 687
			return null;
		}

		if (is_subclass_of($className, 'yii\base\Controller')) {
			return new $className($id, $this);
		} elseif (YII_DEBUG) {
			throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller.");
		} else {
			return null;
		}
resurtm committed
688 689 690
	}

	/**
Qiang Xue committed
691
	 * This method is invoked right before an action of this module is to be executed (after all possible filters.)
resurtm committed
692
	 * You may override this method to do last-minute preparation for the action.
Qiang Xue committed
693
	 * Make sure you call the parent implementation so that the relevant event is triggered.
resurtm committed
694 695 696 697 698
	 * @param Action $action the action to be executed.
	 * @return boolean whether the action should continue to be executed.
	 */
	public function beforeAction($action)
	{
Qiang Xue committed
699
		return true;
resurtm committed
700 701 702
	}

	/**
Qiang Xue committed
703
	 * This method is invoked right after an action of this module has been executed.
resurtm committed
704
	 * You may override this method to do some postprocessing for the action.
Qiang Xue committed
705
	 * Make sure you call the parent implementation so that the relevant event is triggered.
706
	 * Also make sure you return the action result, whether it is processed or not.
resurtm committed
707
	 * @param Action $action the action just executed.
708
	 * @param mixed $result the action return result.
709
	 * @return mixed the processed action result.
resurtm committed
710
	 */
711
	public function afterAction($action, $result)
resurtm committed
712
	{
713
		return $result;
resurtm committed
714 715
	}
}