Controller.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. /**
  10. * Controller is the base class for classes containing controller logic.
  11. *
  12. * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
  13. *
  14. * @property Module[] $modules All ancestor modules that this controller is located within. This property is
  15. * read-only.
  16. * @property string $route The route (module ID, controller ID and action ID) of the current request. This
  17. * property is read-only.
  18. * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
  19. * read-only.
  20. * @property View|\yii\web\View $view The view object that can be used to render views or view files.
  21. * @property string $viewPath The directory containing the view files for this controller.
  22. *
  23. * @author Qiang Xue <qiang.xue@gmail.com>
  24. * @since 2.0
  25. */
  26. class Controller extends Component implements ViewContextInterface
  27. {
  28. /**
  29. * @event ActionEvent an event raised right before executing a controller action.
  30. * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
  31. */
  32. const EVENT_BEFORE_ACTION = 'beforeAction';
  33. /**
  34. * @event ActionEvent an event raised right after executing a controller action.
  35. */
  36. const EVENT_AFTER_ACTION = 'afterAction';
  37. /**
  38. * @var string the ID of this controller.
  39. */
  40. public $id;
  41. /**
  42. * @var Module the module that this controller belongs to.
  43. */
  44. public $module;
  45. /**
  46. * @var string the ID of the action that is used when the action ID is not specified
  47. * in the request. Defaults to 'index'.
  48. */
  49. public $defaultAction = 'index';
  50. /**
  51. * @var null|string|false the name of the layout to be applied to this controller's views.
  52. * This property mainly affects the behavior of [[render()]].
  53. * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
  54. * If false, no layout will be applied.
  55. */
  56. public $layout;
  57. /**
  58. * @var Action the action that is currently being executed. This property will be set
  59. * by [[run()]] when it is called by [[Application]] to run an action.
  60. */
  61. public $action;
  62. /**
  63. * @var View the view object that can be used to render views or view files.
  64. */
  65. private $_view;
  66. /**
  67. * @var string the root directory that contains view files for this controller.
  68. */
  69. private $_viewPath;
  70. /**
  71. * @param string $id the ID of this controller.
  72. * @param Module $module the module that this controller belongs to.
  73. * @param array $config name-value pairs that will be used to initialize the object properties.
  74. */
  75. public function __construct($id, $module, $config = [])
  76. {
  77. $this->id = $id;
  78. $this->module = $module;
  79. parent::__construct($config);
  80. }
  81. /**
  82. * Declares external actions for the controller.
  83. * This method is meant to be overwritten to declare external actions for the controller.
  84. * It should return an array, with array keys being action IDs, and array values the corresponding
  85. * action class names or action configuration arrays. For example,
  86. *
  87. * ```php
  88. * return [
  89. * 'action1' => 'app\components\Action1',
  90. * 'action2' => [
  91. * 'class' => 'app\components\Action2',
  92. * 'property1' => 'value1',
  93. * 'property2' => 'value2',
  94. * ],
  95. * ];
  96. * ```
  97. *
  98. * [[\Yii::createObject()]] will be used later to create the requested action
  99. * using the configuration provided here.
  100. */
  101. public function actions()
  102. {
  103. return [];
  104. }
  105. /**
  106. * Runs an action within this controller with the specified action ID and parameters.
  107. * If the action ID is empty, the method will use [[defaultAction]].
  108. * @param string $id the ID of the action to be executed.
  109. * @param array $params the parameters (name-value pairs) to be passed to the action.
  110. * @return mixed the result of the action.
  111. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
  112. * @see createAction()
  113. */
  114. public function runAction($id, $params = [])
  115. {
  116. $action = $this->createAction($id);
  117. if ($action === null) {
  118. throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
  119. }
  120. Yii::trace('Route to run: ' . $action->getUniqueId(), __METHOD__);
  121. if (Yii::$app->requestedAction === null) {
  122. Yii::$app->requestedAction = $action;
  123. }
  124. $oldAction = $this->action;
  125. $this->action = $action;
  126. $modules = [];
  127. $runAction = true;
  128. // call beforeAction on modules
  129. foreach ($this->getModules() as $module) {
  130. if ($module->beforeAction($action)) {
  131. array_unshift($modules, $module);
  132. } else {
  133. $runAction = false;
  134. break;
  135. }
  136. }
  137. $result = null;
  138. if ($runAction && $this->beforeAction($action)) {
  139. // run the action
  140. $result = $action->runWithParams($params);
  141. $result = $this->afterAction($action, $result);
  142. // call afterAction on modules
  143. foreach ($modules as $module) {
  144. /* @var $module Module */
  145. $result = $module->afterAction($action, $result);
  146. }
  147. }
  148. if ($oldAction !== null) {
  149. $this->action = $oldAction;
  150. }
  151. return $result;
  152. }
  153. /**
  154. * Runs a request specified in terms of a route.
  155. * The route can be either an ID of an action within this controller or a complete route consisting
  156. * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
  157. * the route will start from the application; otherwise, it will start from the parent module of this controller.
  158. * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
  159. * @param array $params the parameters to be passed to the action.
  160. * @return mixed the result of the action.
  161. * @see runAction()
  162. */
  163. public function run($route, $params = [])
  164. {
  165. $pos = strpos($route, '/');
  166. if ($pos === false) {
  167. return $this->runAction($route, $params);
  168. } elseif ($pos > 0) {
  169. return $this->module->runAction($route, $params);
  170. }
  171. return Yii::$app->runAction(ltrim($route, '/'), $params);
  172. }
  173. /**
  174. * Binds the parameters to the action.
  175. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  176. * @param Action $action the action to be bound with parameters.
  177. * @param array $params the parameters to be bound to the action.
  178. * @return array the valid parameters that the action can run with.
  179. */
  180. public function bindActionParams($action, $params)
  181. {
  182. return [];
  183. }
  184. /**
  185. * Creates an action based on the given action ID.
  186. * The method first checks if the action ID has been declared in [[actions()]]. If so,
  187. * it will use the configuration declared there to create the action object.
  188. * If not, it will look for a controller method whose name is in the format of `actionXyz`
  189. * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
  190. * method will be created and returned.
  191. * @param string $id the action ID.
  192. * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
  193. */
  194. public function createAction($id)
  195. {
  196. if ($id === '') {
  197. $id = $this->defaultAction;
  198. }
  199. $actionMap = $this->actions();
  200. if (isset($actionMap[$id])) {
  201. return Yii::createObject($actionMap[$id], [$id, $this]);
  202. } elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
  203. $methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
  204. if (method_exists($this, $methodName)) {
  205. $method = new \ReflectionMethod($this, $methodName);
  206. if ($method->isPublic() && $method->getName() === $methodName) {
  207. return new InlineAction($id, $this, $methodName);
  208. }
  209. }
  210. }
  211. return null;
  212. }
  213. /**
  214. * This method is invoked right before an action is executed.
  215. *
  216. * The method will trigger the [[EVENT_BEFORE_ACTION]] event. The return value of the method
  217. * will determine whether the action should continue to run.
  218. *
  219. * In case the action should not run, the request should be handled inside of the `beforeAction` code
  220. * by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
  221. *
  222. * If you override this method, your code should look like the following:
  223. *
  224. * ```php
  225. * public function beforeAction($action)
  226. * {
  227. * // your custom code here, if you want the code to run before action filters,
  228. * // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
  229. *
  230. * if (!parent::beforeAction($action)) {
  231. * return false;
  232. * }
  233. *
  234. * // other custom code here
  235. *
  236. * return true; // or false to not run the action
  237. * }
  238. * ```
  239. *
  240. * @param Action $action the action to be executed.
  241. * @return bool whether the action should continue to run.
  242. */
  243. public function beforeAction($action)
  244. {
  245. $event = new ActionEvent($action);
  246. $this->trigger(self::EVENT_BEFORE_ACTION, $event);
  247. return $event->isValid;
  248. }
  249. /**
  250. * This method is invoked right after an action is executed.
  251. *
  252. * The method will trigger the [[EVENT_AFTER_ACTION]] event. The return value of the method
  253. * will be used as the action return value.
  254. *
  255. * If you override this method, your code should look like the following:
  256. *
  257. * ```php
  258. * public function afterAction($action, $result)
  259. * {
  260. * $result = parent::afterAction($action, $result);
  261. * // your custom code here
  262. * return $result;
  263. * }
  264. * ```
  265. *
  266. * @param Action $action the action just executed.
  267. * @param mixed $result the action return result.
  268. * @return mixed the processed action result.
  269. */
  270. public function afterAction($action, $result)
  271. {
  272. $event = new ActionEvent($action);
  273. $event->result = $result;
  274. $this->trigger(self::EVENT_AFTER_ACTION, $event);
  275. return $event->result;
  276. }
  277. /**
  278. * Returns all ancestor modules of this controller.
  279. * The first module in the array is the outermost one (i.e., the application instance),
  280. * while the last is the innermost one.
  281. * @return Module[] all ancestor modules that this controller is located within.
  282. */
  283. public function getModules()
  284. {
  285. $modules = [$this->module];
  286. $module = $this->module;
  287. while ($module->module !== null) {
  288. array_unshift($modules, $module->module);
  289. $module = $module->module;
  290. }
  291. return $modules;
  292. }
  293. /**
  294. * Returns the unique ID of the controller.
  295. * @return string the controller ID that is prefixed with the module ID (if any).
  296. */
  297. public function getUniqueId()
  298. {
  299. return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
  300. }
  301. /**
  302. * Returns the route of the current request.
  303. * @return string the route (module ID, controller ID and action ID) of the current request.
  304. */
  305. public function getRoute()
  306. {
  307. return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
  308. }
  309. /**
  310. * Renders a view and applies layout if available.
  311. *
  312. * The view to be rendered can be specified in one of the following formats:
  313. *
  314. * - path alias (e.g. "@app/views/site/index");
  315. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  316. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  317. * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
  318. * The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
  319. * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
  320. *
  321. * To determine which layout should be applied, the following two steps are conducted:
  322. *
  323. * 1. In the first step, it determines the layout name and the context module:
  324. *
  325. * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
  326. * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
  327. * module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
  328. * are used as the layout name and the context module, respectively. If such a module is not found
  329. * or the corresponding layout is not a string, it will return false, meaning no applicable layout.
  330. *
  331. * 2. In the second step, it determines the actual layout file according to the previously found layout name
  332. * and context module. The layout name can be:
  333. *
  334. * - a path alias (e.g. "@app/views/layouts/main");
  335. * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
  336. * looked for under the [[Application::layoutPath|layout path]] of the application;
  337. * - a relative path (e.g. "main"): the actual layout file will be looked for under the
  338. * [[Module::layoutPath|layout path]] of the context module.
  339. *
  340. * If the layout name does not contain a file extension, it will use the default one `.php`.
  341. *
  342. * @param string $view the view name.
  343. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  344. * These parameters will not be available in the layout.
  345. * @return string the rendering result.
  346. * @throws InvalidParamException if the view file or the layout file does not exist.
  347. */
  348. public function render($view, $params = [])
  349. {
  350. $content = $this->getView()->render($view, $params, $this);
  351. return $this->renderContent($content);
  352. }
  353. /**
  354. * Renders a static string by applying a layout.
  355. * @param string $content the static string being rendered
  356. * @return string the rendering result of the layout with the given static string as the `$content` variable.
  357. * If the layout is disabled, the string will be returned back.
  358. * @since 2.0.1
  359. */
  360. public function renderContent($content)
  361. {
  362. $layoutFile = $this->findLayoutFile($this->getView());
  363. if ($layoutFile !== false) {
  364. return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
  365. }
  366. return $content;
  367. }
  368. /**
  369. * Renders a view without applying layout.
  370. * This method differs from [[render()]] in that it does not apply any layout.
  371. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  372. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  373. * @return string the rendering result.
  374. * @throws InvalidParamException if the view file does not exist.
  375. */
  376. public function renderPartial($view, $params = [])
  377. {
  378. return $this->getView()->render($view, $params, $this);
  379. }
  380. /**
  381. * Renders a view file.
  382. * @param string $file the view file to be rendered. This can be either a file path or a path alias.
  383. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  384. * @return string the rendering result.
  385. * @throws InvalidParamException if the view file does not exist.
  386. */
  387. public function renderFile($file, $params = [])
  388. {
  389. return $this->getView()->renderFile($file, $params, $this);
  390. }
  391. /**
  392. * Returns the view object that can be used to render views or view files.
  393. * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
  394. * this view object to implement the actual view rendering.
  395. * If not set, it will default to the "view" application component.
  396. * @return View|\yii\web\View the view object that can be used to render views or view files.
  397. */
  398. public function getView()
  399. {
  400. if ($this->_view === null) {
  401. $this->_view = Yii::$app->getView();
  402. }
  403. return $this->_view;
  404. }
  405. /**
  406. * Sets the view object to be used by this controller.
  407. * @param View|\yii\web\View $view the view object that can be used to render views or view files.
  408. */
  409. public function setView($view)
  410. {
  411. $this->_view = $view;
  412. }
  413. /**
  414. * Returns the directory containing view files for this controller.
  415. * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
  416. * [[viewPath]] directory.
  417. * @return string the directory containing the view files for this controller.
  418. */
  419. public function getViewPath()
  420. {
  421. if ($this->_viewPath === null) {
  422. $this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
  423. }
  424. return $this->_viewPath;
  425. }
  426. /**
  427. * Sets the directory that contains the view files.
  428. * @param string $path the root directory of view files.
  429. * @throws InvalidParamException if the directory is invalid
  430. * @since 2.0.7
  431. */
  432. public function setViewPath($path)
  433. {
  434. $this->_viewPath = Yii::getAlias($path);
  435. }
  436. /**
  437. * Finds the applicable layout file.
  438. * @param View $view the view object to render the layout file.
  439. * @return string|bool the layout file path, or false if layout is not needed.
  440. * Please refer to [[render()]] on how to specify this parameter.
  441. * @throws InvalidParamException if an invalid path alias is used to specify the layout.
  442. */
  443. public function findLayoutFile($view)
  444. {
  445. $module = $this->module;
  446. if (is_string($this->layout)) {
  447. $layout = $this->layout;
  448. } elseif ($this->layout === null) {
  449. while ($module !== null && $module->layout === null) {
  450. $module = $module->module;
  451. }
  452. if ($module !== null && is_string($module->layout)) {
  453. $layout = $module->layout;
  454. }
  455. }
  456. if (!isset($layout)) {
  457. return false;
  458. }
  459. if (strncmp($layout, '@', 1) === 0) {
  460. $file = Yii::getAlias($layout);
  461. } elseif (strncmp($layout, '/', 1) === 0) {
  462. $file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
  463. } else {
  464. $file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
  465. }
  466. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  467. return $file;
  468. }
  469. $path = $file . '.' . $view->defaultExtension;
  470. if ($view->defaultExtension !== 'php' && !is_file($path)) {
  471. $path = $file . '.php';
  472. }
  473. return $path;
  474. }
  475. }