Module.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use yii\di\ServiceLocator;
  10. /**
  11. * Module is the base class for module and application classes.
  12. *
  13. * A module represents a sub-application which contains MVC elements by itself, such as
  14. * models, views, controllers, etc.
  15. *
  16. * A module may consist of [[modules|sub-modules]].
  17. *
  18. * [[components|Components]] may be registered with the module so that they are globally
  19. * accessible within the module.
  20. *
  21. * For more details and usage information on Module, see the [guide article on modules](guide:structure-modules).
  22. *
  23. * @property array $aliases List of path aliases to be defined. The array keys are alias names (must start
  24. * with `@`) and the array values are the corresponding paths or aliases. See [[setAliases()]] for an example.
  25. * This property is write-only.
  26. * @property string $basePath The root directory of the module.
  27. * @property string $controllerPath The directory that contains the controller classes. This property is
  28. * read-only.
  29. * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts".
  30. * @property array $modules The modules (indexed by their IDs).
  31. * @property string $uniqueId The unique ID of the module. This property is read-only.
  32. * @property string $version The version of this module. Note that the type of this property differs in getter
  33. * and setter. See [[getVersion()]] and [[setVersion()]] for details.
  34. * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/views".
  35. *
  36. * @author Qiang Xue <qiang.xue@gmail.com>
  37. * @since 2.0
  38. */
  39. class Module extends ServiceLocator
  40. {
  41. /**
  42. * @event ActionEvent an event raised before executing a controller action.
  43. * You may set [[ActionEvent::isValid]] to be `false` to cancel the action execution.
  44. */
  45. const EVENT_BEFORE_ACTION = 'beforeAction';
  46. /**
  47. * @event ActionEvent an event raised after executing a controller action.
  48. */
  49. const EVENT_AFTER_ACTION = 'afterAction';
  50. /**
  51. * @var array custom module parameters (name => value).
  52. */
  53. public $params = [];
  54. /**
  55. * @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
  56. */
  57. public $id;
  58. /**
  59. * @var Module the parent module of this module. `null` if this module does not have a parent.
  60. */
  61. public $module;
  62. /**
  63. * @var string|bool the layout that should be applied for views within this module. This refers to a view name
  64. * relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
  65. * will be taken. If this is `false`, layout will be disabled within this module.
  66. */
  67. public $layout;
  68. /**
  69. * @var array mapping from controller ID to controller configurations.
  70. * Each name-value pair specifies the configuration of a single controller.
  71. * A controller configuration can be either a string or an array.
  72. * If the former, the string should be the fully qualified class name of the controller.
  73. * If the latter, the array must contain a `class` element which specifies
  74. * the controller's fully qualified class name, and the rest of the name-value pairs
  75. * in the array are used to initialize the corresponding controller properties. For example,
  76. *
  77. * ```php
  78. * [
  79. * 'account' => 'app\controllers\UserController',
  80. * 'article' => [
  81. * 'class' => 'app\controllers\PostController',
  82. * 'pageTitle' => 'something new',
  83. * ],
  84. * ]
  85. * ```
  86. */
  87. public $controllerMap = [];
  88. /**
  89. * @var string the namespace that controller classes are in.
  90. * This namespace will be used to load controller classes by prepending it to the controller
  91. * class name.
  92. *
  93. * If not set, it will use the `controllers` sub-namespace under the namespace of this module.
  94. * For example, if the namespace of this module is `foo\bar`, then the default
  95. * controller namespace would be `foo\bar\controllers`.
  96. *
  97. * See also the [guide section on autoloading](guide:concept-autoloading) to learn more about
  98. * defining namespaces and how classes are loaded.
  99. */
  100. public $controllerNamespace;
  101. /**
  102. * @var string the default route of this module. Defaults to `default`.
  103. * The route may consist of child module ID, controller ID, and/or action ID.
  104. * For example, `help`, `post/create`, `admin/post/create`.
  105. * If action ID is not given, it will take the default value as specified in
  106. * [[Controller::defaultAction]].
  107. */
  108. public $defaultRoute = 'default';
  109. /**
  110. * @var string the root directory of the module.
  111. */
  112. private $_basePath;
  113. /**
  114. * @var string the root directory that contains view files for this module
  115. */
  116. private $_viewPath;
  117. /**
  118. * @var string the root directory that contains layout view files for this module.
  119. */
  120. private $_layoutPath;
  121. /**
  122. * @var array child modules of this module
  123. */
  124. private $_modules = [];
  125. /**
  126. * @var string|callable the version of this module.
  127. * Version can be specified as a PHP callback, which can accept module instance as an argument and should
  128. * return the actual version. For example:
  129. *
  130. * ```php
  131. * function (Module $module) {
  132. * //return string|int
  133. * }
  134. * ```
  135. *
  136. * If not set, [[defaultVersion()]] will be used to determine actual value.
  137. *
  138. * @since 2.0.11
  139. */
  140. private $_version;
  141. /**
  142. * Constructor.
  143. * @param string $id the ID of this module.
  144. * @param Module $parent the parent module (if any).
  145. * @param array $config name-value pairs that will be used to initialize the object properties.
  146. */
  147. public function __construct($id, $parent = null, $config = [])
  148. {
  149. $this->id = $id;
  150. $this->module = $parent;
  151. parent::__construct($config);
  152. }
  153. /**
  154. * Returns the currently requested instance of this module class.
  155. * If the module class is not currently requested, `null` will be returned.
  156. * This method is provided so that you access the module instance from anywhere within the module.
  157. * @return static|null the currently requested instance of this module class, or `null` if the module class is not requested.
  158. */
  159. public static function getInstance()
  160. {
  161. $class = get_called_class();
  162. return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
  163. }
  164. /**
  165. * Sets the currently requested instance of this module class.
  166. * @param Module|null $instance the currently requested instance of this module class.
  167. * If it is `null`, the instance of the calling class will be removed, if any.
  168. */
  169. public static function setInstance($instance)
  170. {
  171. if ($instance === null) {
  172. unset(Yii::$app->loadedModules[get_called_class()]);
  173. } else {
  174. Yii::$app->loadedModules[get_class($instance)] = $instance;
  175. }
  176. }
  177. /**
  178. * Initializes the module.
  179. *
  180. * This method is called after the module is created and initialized with property values
  181. * given in configuration. The default implementation will initialize [[controllerNamespace]]
  182. * if it is not set.
  183. *
  184. * If you override this method, please make sure you call the parent implementation.
  185. */
  186. public function init()
  187. {
  188. if ($this->controllerNamespace === null) {
  189. $class = get_class($this);
  190. if (($pos = strrpos($class, '\\')) !== false) {
  191. $this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
  192. }
  193. }
  194. }
  195. /**
  196. * Returns an ID that uniquely identifies this module among all modules within the current application.
  197. * Note that if the module is an application, an empty string will be returned.
  198. * @return string the unique ID of the module.
  199. */
  200. public function getUniqueId()
  201. {
  202. return $this->module ? ltrim($this->module->getUniqueId() . '/' . $this->id, '/') : $this->id;
  203. }
  204. /**
  205. * Returns the root directory of the module.
  206. * It defaults to the directory containing the module class file.
  207. * @return string the root directory of the module.
  208. */
  209. public function getBasePath()
  210. {
  211. if ($this->_basePath === null) {
  212. $class = new \ReflectionClass($this);
  213. $this->_basePath = dirname($class->getFileName());
  214. }
  215. return $this->_basePath;
  216. }
  217. /**
  218. * Sets the root directory of the module.
  219. * This method can only be invoked at the beginning of the constructor.
  220. * @param string $path the root directory of the module. This can be either a directory name or a [path alias](guide:concept-aliases).
  221. * @throws InvalidArgumentException if the directory does not exist.
  222. */
  223. public function setBasePath($path)
  224. {
  225. $path = Yii::getAlias($path);
  226. $p = strncmp($path, 'phar://', 7) === 0 ? $path : realpath($path);
  227. if ($p !== false && is_dir($p)) {
  228. $this->_basePath = $p;
  229. } else {
  230. throw new InvalidArgumentException("The directory does not exist: $path");
  231. }
  232. }
  233. /**
  234. * Returns the directory that contains the controller classes according to [[controllerNamespace]].
  235. * Note that in order for this method to return a value, you must define
  236. * an alias for the root namespace of [[controllerNamespace]].
  237. * @return string the directory that contains the controller classes.
  238. * @throws InvalidArgumentException if there is no alias defined for the root namespace of [[controllerNamespace]].
  239. */
  240. public function getControllerPath()
  241. {
  242. return Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
  243. }
  244. /**
  245. * Returns the directory that contains the view files for this module.
  246. * @return string the root directory of view files. Defaults to "[[basePath]]/views".
  247. */
  248. public function getViewPath()
  249. {
  250. if ($this->_viewPath === null) {
  251. $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
  252. }
  253. return $this->_viewPath;
  254. }
  255. /**
  256. * Sets the directory that contains the view files.
  257. * @param string $path the root directory of view files.
  258. * @throws InvalidArgumentException if the directory is invalid.
  259. */
  260. public function setViewPath($path)
  261. {
  262. $this->_viewPath = Yii::getAlias($path);
  263. }
  264. /**
  265. * Returns the directory that contains layout view files for this module.
  266. * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
  267. */
  268. public function getLayoutPath()
  269. {
  270. if ($this->_layoutPath === null) {
  271. $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
  272. }
  273. return $this->_layoutPath;
  274. }
  275. /**
  276. * Sets the directory that contains the layout files.
  277. * @param string $path the root directory or [path alias](guide:concept-aliases) of layout files.
  278. * @throws InvalidArgumentException if the directory is invalid
  279. */
  280. public function setLayoutPath($path)
  281. {
  282. $this->_layoutPath = Yii::getAlias($path);
  283. }
  284. /**
  285. * Returns current module version.
  286. * If version is not explicitly set, [[defaultVersion()]] method will be used to determine its value.
  287. * @return string the version of this module.
  288. * @since 2.0.11
  289. */
  290. public function getVersion()
  291. {
  292. if ($this->_version === null) {
  293. $this->_version = $this->defaultVersion();
  294. } else {
  295. if (!is_scalar($this->_version)) {
  296. $this->_version = call_user_func($this->_version, $this);
  297. }
  298. }
  299. return $this->_version;
  300. }
  301. /**
  302. * Sets current module version.
  303. * @param string|callable $version the version of this module.
  304. * Version can be specified as a PHP callback, which can accept module instance as an argument and should
  305. * return the actual version. For example:
  306. *
  307. * ```php
  308. * function (Module $module) {
  309. * //return string
  310. * }
  311. * ```
  312. *
  313. * @since 2.0.11
  314. */
  315. public function setVersion($version)
  316. {
  317. $this->_version = $version;
  318. }
  319. /**
  320. * Returns default module version.
  321. * Child class may override this method to provide more specific version detection.
  322. * @return string the version of this module.
  323. * @since 2.0.11
  324. */
  325. protected function defaultVersion()
  326. {
  327. if ($this->module === null) {
  328. return '1.0';
  329. }
  330. return $this->module->getVersion();
  331. }
  332. /**
  333. * Defines path aliases.
  334. * This method calls [[Yii::setAlias()]] to register the path aliases.
  335. * This method is provided so that you can define path aliases when configuring a module.
  336. * @property array list of path aliases to be defined. The array keys are alias names
  337. * (must start with `@`) and the array values are the corresponding paths or aliases.
  338. * See [[setAliases()]] for an example.
  339. * @param array $aliases list of path aliases to be defined. The array keys are alias names
  340. * (must start with `@`) and the array values are the corresponding paths or aliases.
  341. * For example,
  342. *
  343. * ```php
  344. * [
  345. * '@models' => '@app/models', // an existing alias
  346. * '@backend' => __DIR__ . '/../backend', // a directory
  347. * ]
  348. * ```
  349. */
  350. public function setAliases($aliases)
  351. {
  352. foreach ($aliases as $name => $alias) {
  353. Yii::setAlias($name, $alias);
  354. }
  355. }
  356. /**
  357. * Checks whether the child module of the specified ID exists.
  358. * This method supports checking the existence of both child and grand child modules.
  359. * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
  360. * @return bool whether the named module exists. Both loaded and unloaded modules
  361. * are considered.
  362. */
  363. public function hasModule($id)
  364. {
  365. if (($pos = strpos($id, '/')) !== false) {
  366. // sub-module
  367. $module = $this->getModule(substr($id, 0, $pos));
  368. return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
  369. }
  370. return isset($this->_modules[$id]);
  371. }
  372. /**
  373. * Retrieves the child module of the specified ID.
  374. * This method supports retrieving both child modules and grand child modules.
  375. * @param string $id module ID (case-sensitive). To retrieve grand child modules,
  376. * use ID path relative to this module (e.g. `admin/content`).
  377. * @param bool $load whether to load the module if it is not yet loaded.
  378. * @return Module|null the module instance, `null` if the module does not exist.
  379. * @see hasModule()
  380. */
  381. public function getModule($id, $load = true)
  382. {
  383. if (($pos = strpos($id, '/')) !== false) {
  384. // sub-module
  385. $module = $this->getModule(substr($id, 0, $pos));
  386. return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
  387. }
  388. if (isset($this->_modules[$id])) {
  389. if ($this->_modules[$id] instanceof self) {
  390. return $this->_modules[$id];
  391. } elseif ($load) {
  392. Yii::debug("Loading module: $id", __METHOD__);
  393. /* @var $module Module */
  394. $module = Yii::createObject($this->_modules[$id], [$id, $this]);
  395. $module->setInstance($module);
  396. return $this->_modules[$id] = $module;
  397. }
  398. }
  399. return null;
  400. }
  401. /**
  402. * Adds a sub-module to this module.
  403. * @param string $id module ID.
  404. * @param Module|array|null $module the sub-module to be added to this module. This can
  405. * be one of the following:
  406. *
  407. * - a [[Module]] object
  408. * - a configuration array: when [[getModule()]] is called initially, the array
  409. * will be used to instantiate the sub-module
  410. * - `null`: the named sub-module will be removed from this module
  411. */
  412. public function setModule($id, $module)
  413. {
  414. if ($module === null) {
  415. unset($this->_modules[$id]);
  416. } else {
  417. $this->_modules[$id] = $module;
  418. }
  419. }
  420. /**
  421. * Returns the sub-modules in this module.
  422. * @param bool $loadedOnly whether to return the loaded sub-modules only. If this is set `false`,
  423. * then all sub-modules registered in this module will be returned, whether they are loaded or not.
  424. * Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
  425. * @return array the modules (indexed by their IDs).
  426. */
  427. public function getModules($loadedOnly = false)
  428. {
  429. if ($loadedOnly) {
  430. $modules = [];
  431. foreach ($this->_modules as $module) {
  432. if ($module instanceof self) {
  433. $modules[] = $module;
  434. }
  435. }
  436. return $modules;
  437. }
  438. return $this->_modules;
  439. }
  440. /**
  441. * Registers sub-modules in the current module.
  442. *
  443. * Each sub-module should be specified as a name-value pair, where
  444. * name refers to the ID of the module and value the module or a configuration
  445. * array that can be used to create the module. In the latter case, [[Yii::createObject()]]
  446. * will be used to create the module.
  447. *
  448. * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
  449. *
  450. * The following is an example for registering two sub-modules:
  451. *
  452. * ```php
  453. * [
  454. * 'comment' => [
  455. * 'class' => 'app\modules\comment\CommentModule',
  456. * 'db' => 'db',
  457. * ],
  458. * 'booking' => ['class' => 'app\modules\booking\BookingModule'],
  459. * ]
  460. * ```
  461. *
  462. * @param array $modules modules (id => module configuration or instances).
  463. */
  464. public function setModules($modules)
  465. {
  466. foreach ($modules as $id => $module) {
  467. $this->_modules[$id] = $module;
  468. }
  469. }
  470. /**
  471. * Runs a controller action specified by a route.
  472. * This method parses the specified route and creates the corresponding child module(s), controller and action
  473. * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
  474. * If the route is empty, the method will use [[defaultRoute]].
  475. * @param string $route the route that specifies the action.
  476. * @param array $params the parameters to be passed to the action
  477. * @return mixed the result of the action.
  478. * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully.
  479. */
  480. public function runAction($route, $params = [])
  481. {
  482. $parts = $this->createController($route);
  483. if (is_array($parts)) {
  484. /* @var $controller Controller */
  485. list($controller, $actionID) = $parts;
  486. $oldController = Yii::$app->controller;
  487. Yii::$app->controller = $controller;
  488. $result = $controller->runAction($actionID, $params);
  489. if ($oldController !== null) {
  490. Yii::$app->controller = $oldController;
  491. }
  492. return $result;
  493. }
  494. $id = $this->getUniqueId();
  495. throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".');
  496. }
  497. /**
  498. * Creates a controller instance based on the given route.
  499. *
  500. * The route should be relative to this module. The method implements the following algorithm
  501. * to resolve the given route:
  502. *
  503. * 1. If the route is empty, use [[defaultRoute]];
  504. * 2. If the first segment of the route is found in [[controllerMap]], create a controller
  505. * based on the corresponding configuration found in [[controllerMap]];
  506. * 3. If the first segment of the route is a valid module ID as declared in [[modules]],
  507. * call the module's `createController()` with the rest part of the route;
  508. * 4. The given route is in the format of `abc/def/xyz`. Try either `abc\DefController`
  509. * or `abc\def\XyzController` class within the [[controllerNamespace|controller namespace]].
  510. *
  511. * If any of the above steps resolves into a controller, it is returned together with the rest
  512. * part of the route which will be treated as the action ID. Otherwise, `false` will be returned.
  513. *
  514. * @param string $route the route consisting of module, controller and action IDs.
  515. * @return array|bool If the controller is created successfully, it will be returned together
  516. * with the requested action ID. Otherwise `false` will be returned.
  517. * @throws InvalidConfigException if the controller class and its file do not match.
  518. */
  519. public function createController($route)
  520. {
  521. if ($route === '') {
  522. $route = $this->defaultRoute;
  523. }
  524. // double slashes or leading/ending slashes may cause substr problem
  525. $route = trim($route, '/');
  526. if (strpos($route, '//') !== false) {
  527. return false;
  528. }
  529. if (strpos($route, '/') !== false) {
  530. list($id, $route) = explode('/', $route, 2);
  531. } else {
  532. $id = $route;
  533. $route = '';
  534. }
  535. // module and controller map take precedence
  536. if (isset($this->controllerMap[$id])) {
  537. $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
  538. return [$controller, $route];
  539. }
  540. $module = $this->getModule($id);
  541. if ($module !== null) {
  542. return $module->createController($route);
  543. }
  544. if (($pos = strrpos($route, '/')) !== false) {
  545. $id .= '/' . substr($route, 0, $pos);
  546. $route = substr($route, $pos + 1);
  547. }
  548. $controller = $this->createControllerByID($id);
  549. if ($controller === null && $route !== '') {
  550. $controller = $this->createControllerByID($id . '/' . $route);
  551. $route = '';
  552. }
  553. return $controller === null ? false : [$controller, $route];
  554. }
  555. /**
  556. * Creates a controller based on the given controller ID.
  557. *
  558. * The controller ID is relative to this module. The controller class
  559. * should be namespaced under [[controllerNamespace]].
  560. *
  561. * Note that this method does not check [[modules]] or [[controllerMap]].
  562. *
  563. * @param string $id the controller ID.
  564. * @return Controller|null the newly created controller instance, or `null` if the controller ID is invalid.
  565. * @throws InvalidConfigException if the controller class and its file name do not match.
  566. * This exception is only thrown when in debug mode.
  567. */
  568. public function createControllerByID($id)
  569. {
  570. $pos = strrpos($id, '/');
  571. if ($pos === false) {
  572. $prefix = '';
  573. $className = $id;
  574. } else {
  575. $prefix = substr($id, 0, $pos + 1);
  576. $className = substr($id, $pos + 1);
  577. }
  578. if ($this->isIncorrectClassNameOrPrefix($className, $prefix)) {
  579. return null;
  580. }
  581. $className = preg_replace_callback('%-([a-z0-9_])%i', function ($matches) {
  582. return ucfirst($matches[1]);
  583. }, ucfirst($className)) . 'Controller';
  584. $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
  585. if (strpos($className, '-') !== false || !class_exists($className)) {
  586. return null;
  587. }
  588. if (is_subclass_of($className, 'yii\base\Controller')) {
  589. $controller = Yii::createObject($className, [$id, $this]);
  590. return get_class($controller) === $className ? $controller : null;
  591. } elseif (YII_DEBUG) {
  592. throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
  593. }
  594. return null;
  595. }
  596. /**
  597. * Checks if class name or prefix is incorrect
  598. *
  599. * @param string $className
  600. * @param string $prefix
  601. * @return bool
  602. */
  603. private function isIncorrectClassNameOrPrefix($className, $prefix)
  604. {
  605. if (!preg_match('%^[a-z][a-z0-9\\-_]*$%', $className)) {
  606. return true;
  607. }
  608. if ($prefix !== '' && !preg_match('%^[a-z0-9_/]+$%i', $prefix)) {
  609. return true;
  610. }
  611. return false;
  612. }
  613. /**
  614. * This method is invoked right before an action within this module is executed.
  615. *
  616. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  617. * will determine whether the action should continue to run.
  618. *
  619. * In case the action should not run, the request should be handled inside of the `beforeAction` code
  620. * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
  621. *
  622. * If you override this method, your code should look like the following:
  623. *
  624. * ```php
  625. * public function beforeAction($action)
  626. * {
  627. * if (!parent::beforeAction($action)) {
  628. * return false;
  629. * }
  630. *
  631. * // your custom code here
  632. *
  633. * return true; // or false to not run the action
  634. * }
  635. * ```
  636. *
  637. * @param Action $action the action to be executed.
  638. * @return bool whether the action should continue to be executed.
  639. */
  640. public function beforeAction($action)
  641. {
  642. $event = new ActionEvent($action);
  643. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  644. return $event->isValid;
  645. }
  646. /**
  647. * This method is invoked right after an action within this module is executed.
  648. *
  649. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  650. * will be used as the action return value.
  651. *
  652. * If you override this method, your code should look like the following:
  653. *
  654. * ```php
  655. * public function afterAction($action, $result)
  656. * {
  657. * $result = parent::afterAction($action, $result);
  658. * // your custom code here
  659. * return $result;
  660. * }
  661. * ```
  662. *
  663. * @param Action $action the action just executed.
  664. * @param mixed $result the action return result.
  665. * @return mixed the processed action result.
  666. */
  667. public function afterAction($action, $result)
  668. {
  669. $event = new ActionEvent($action);
  670. $event->result = $result;
  671. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  672. return $event->result;
  673. }
  674. /**
  675. * {@inheritdoc}
  676. *
  677. * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
  678. * The parent module may be the application.
  679. */
  680. public function get($id, $throwException = true)
  681. {
  682. if (!isset($this->module)) {
  683. return parent::get($id, $throwException);
  684. }
  685. $component = parent::get($id, false);
  686. if ($component === null) {
  687. $component = $this->module->get($id, $throwException);
  688. }
  689. return $component;
  690. }
  691. /**
  692. * {@inheritdoc}
  693. *
  694. * Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module.
  695. * The parent module may be the application.
  696. */
  697. public function has($id, $checkInstance = false)
  698. {
  699. return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
  700. }
  701. }