Controller.php 22 KB

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