You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

641 line
24KB

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