Controller.php 15 KB

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