Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. * ~~~
  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 = 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. return $this->_viewPath;
  232. } else {
  233. return $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
  234. }
  235. }
  236. /**
  237. * Sets the directory that contains the view files.
  238. * @param string $path the root directory of view files.
  239. * @throws InvalidParamException if the directory is invalid
  240. */
  241. public function setViewPath($path)
  242. {
  243. $this->_viewPath = Yii::getAlias($path);
  244. }
  245. /**
  246. * Returns the directory that contains layout view files for this module.
  247. * @return string the root directory of layout files. Defaults to "[[viewPath]]/layouts".
  248. */
  249. public function getLayoutPath()
  250. {
  251. if ($this->_layoutPath !== null) {
  252. return $this->_layoutPath;
  253. } else {
  254. return $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
  255. }
  256. }
  257. /**
  258. * Sets the directory that contains the layout files.
  259. * @param string $path the root directory or path alias of layout files.
  260. * @throws InvalidParamException if the directory is invalid
  261. */
  262. public function setLayoutPath($path)
  263. {
  264. $this->_layoutPath = Yii::getAlias($path);
  265. }
  266. /**
  267. * Defines path aliases.
  268. * This method calls [[Yii::setAlias()]] to register the path aliases.
  269. * This method is provided so that you can define path aliases when configuring a module.
  270. * @property array list of path aliases to be defined. The array keys are alias names
  271. * (must start with '@') and the array values are the corresponding paths or aliases.
  272. * See [[setAliases()]] for an example.
  273. * @param array $aliases list of path aliases to be defined. The array keys are alias names
  274. * (must start with '@') and the array values are the corresponding paths or aliases.
  275. * For example,
  276. *
  277. * ~~~
  278. * [
  279. * '@models' => '@app/models', // an existing alias
  280. * '@backend' => __DIR__ . '/../backend', // a directory
  281. * ]
  282. * ~~~
  283. */
  284. public function setAliases($aliases)
  285. {
  286. foreach ($aliases as $name => $alias) {
  287. Yii::setAlias($name, $alias);
  288. }
  289. }
  290. /**
  291. * Checks whether the child module of the specified ID exists.
  292. * This method supports checking the existence of both child and grand child modules.
  293. * @param string $id module ID. For grand child modules, use ID path relative to this module (e.g. `admin/content`).
  294. * @return boolean whether the named module exists. Both loaded and unloaded modules
  295. * are considered.
  296. */
  297. public function hasModule($id)
  298. {
  299. if (($pos = strpos($id, '/')) !== false) {
  300. // sub-module
  301. $module = $this->getModule(substr($id, 0, $pos));
  302. return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
  303. } else {
  304. return isset($this->_modules[$id]);
  305. }
  306. }
  307. /**
  308. * Retrieves the child module of the specified ID.
  309. * This method supports retrieving both child modules and grand child modules.
  310. * @param string $id module ID (case-sensitive). To retrieve grand child modules,
  311. * use ID path relative to this module (e.g. `admin/content`).
  312. * @param boolean $load whether to load the module if it is not yet loaded.
  313. * @return Module|null the module instance, null if the module does not exist.
  314. * @see hasModule()
  315. */
  316. public function getModule($id, $load = true)
  317. {
  318. if (($pos = strpos($id, '/')) !== false) {
  319. // sub-module
  320. $module = $this->getModule(substr($id, 0, $pos));
  321. return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
  322. }
  323. if (isset($this->_modules[$id])) {
  324. if ($this->_modules[$id] instanceof Module) {
  325. return $this->_modules[$id];
  326. } elseif ($load) {
  327. Yii::trace("Loading module: $id", __METHOD__);
  328. /* @var $module Module */
  329. $module = Yii::createObject($this->_modules[$id], [$id, $this]);
  330. $module->setInstance($module);
  331. return $this->_modules[$id] = $module;
  332. }
  333. }
  334. return null;
  335. }
  336. /**
  337. * Adds a sub-module to this module.
  338. * @param string $id module ID
  339. * @param Module|array|null $module the sub-module to be added to this module. This can
  340. * be one of the followings:
  341. *
  342. * - a [[Module]] object
  343. * - a configuration array: when [[getModule()]] is called initially, the array
  344. * will be used to instantiate the sub-module
  345. * - null: the named sub-module will be removed from this module
  346. */
  347. public function setModule($id, $module)
  348. {
  349. if ($module === null) {
  350. unset($this->_modules[$id]);
  351. } else {
  352. $this->_modules[$id] = $module;
  353. }
  354. }
  355. /**
  356. * Returns the sub-modules in this module.
  357. * @param boolean $loadedOnly whether to return the loaded sub-modules only. If this is set false,
  358. * then all sub-modules registered in this module will be returned, whether they are loaded or not.
  359. * Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
  360. * @return array the modules (indexed by their IDs)
  361. */
  362. public function getModules($loadedOnly = false)
  363. {
  364. if ($loadedOnly) {
  365. $modules = [];
  366. foreach ($this->_modules as $module) {
  367. if ($module instanceof Module) {
  368. $modules[] = $module;
  369. }
  370. }
  371. return $modules;
  372. } else {
  373. return $this->_modules;
  374. }
  375. }
  376. /**
  377. * Registers sub-modules in the current module.
  378. *
  379. * Each sub-module should be specified as a name-value pair, where
  380. * name refers to the ID of the module and value the module or a configuration
  381. * array that can be used to create the module. In the latter case, [[Yii::createObject()]]
  382. * will be used to create the module.
  383. *
  384. * If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
  385. *
  386. * The following is an example for registering two sub-modules:
  387. *
  388. * ~~~
  389. * [
  390. * 'comment' => [
  391. * 'class' => 'app\modules\comment\CommentModule',
  392. * 'db' => 'db',
  393. * ],
  394. * 'booking' => ['class' => 'app\modules\booking\BookingModule'],
  395. * ]
  396. * ~~~
  397. *
  398. * @param array $modules modules (id => module configuration or instances)
  399. */
  400. public function setModules($modules)
  401. {
  402. foreach ($modules as $id => $module) {
  403. $this->_modules[$id] = $module;
  404. }
  405. }
  406. /**
  407. * Runs a controller action specified by a route.
  408. * This method parses the specified route and creates the corresponding child module(s), controller and action
  409. * instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
  410. * If the route is empty, the method will use [[defaultRoute]].
  411. * @param string $route the route that specifies the action.
  412. * @param array $params the parameters to be passed to the action
  413. * @return mixed the result of the action.
  414. * @throws InvalidRouteException if the requested route cannot be resolved into an action successfully
  415. */
  416. public function runAction($route, $params = [])
  417. {
  418. $parts = $this->createController($route);
  419. if (is_array($parts)) {
  420. /* @var $controller Controller */
  421. list($controller, $actionID) = $parts;
  422. $oldController = Yii::$app->controller;
  423. Yii::$app->controller = $controller;
  424. $result = $controller->runAction($actionID, $params);
  425. Yii::$app->controller = $oldController;
  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. return Yii::createObject($className, [$id, $this]);
  526. } elseif (YII_DEBUG) {
  527. throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller.");
  528. } else {
  529. return null;
  530. }
  531. }
  532. /**
  533. * This method is invoked right before an action within this module is executed.
  534. *
  535. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  536. * will determine whether the action should continue to run.
  537. *
  538. * If you override this method, your code should look like the following:
  539. *
  540. * ```php
  541. * public function beforeAction($action)
  542. * {
  543. * if (parent::beforeAction($action)) {
  544. * // your custom code here
  545. * return true; // or false if needed
  546. * } else {
  547. * return false;
  548. * }
  549. * }
  550. * ```
  551. *
  552. * @param Action $action the action to be executed.
  553. * @return boolean whether the action should continue to be executed.
  554. */
  555. public function beforeAction($action)
  556. {
  557. $event = new ActionEvent($action);
  558. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  559. return $event->isValid;
  560. }
  561. /**
  562. * This method is invoked right after an action within this module is executed.
  563. *
  564. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  565. * will be used as the action return value.
  566. *
  567. * If you override this method, your code should look like the following:
  568. *
  569. * ```php
  570. * public function afterAction($action, $result)
  571. * {
  572. * $result = parent::afterAction($action, $result);
  573. * // your custom code here
  574. * return $result;
  575. * }
  576. * ```
  577. *
  578. * @param Action $action the action just executed.
  579. * @param mixed $result the action return result.
  580. * @return mixed the processed action result.
  581. */
  582. public function afterAction($action, $result)
  583. {
  584. $event = new ActionEvent($action);
  585. $event->result = $result;
  586. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  587. return $event->result;
  588. }
  589. }