Controller.php 15.2 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
10 11
use Yii;

Qiang Xue committed
12
/**
Qiang Xue committed
13
 * Controller is the base class for classes containing controller logic.
Qiang Xue committed
14
 *
15 16 17 18
 * @property string $route The route (module ID, controller ID and action ID) of the current request. This
 * property is read-only.
 * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
 * read-only.
19
 * @property View $view The view object that can be used to render views or view files.
20 21
 * @property string $viewPath The directory containing the view files for this controller. This property is
 * read-only.
22
 *
Qiang Xue committed
23 24 25
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
26
class Controller extends Component implements ViewContextInterface
Qiang Xue committed
27
{
28 29 30 31 32 33 34 35 36
	/**
	 * @event ActionEvent an event raised right before executing a controller action.
	 * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
	 */
	const EVENT_BEFORE_ACTION = 'beforeAction';
	/**
	 * @event ActionEvent an event raised right after executing a controller action.
	 */
	const EVENT_AFTER_ACTION = 'afterAction';
Qiang Xue committed
37
	/**
38
	 * @var string the ID of this controller.
Qiang Xue committed
39 40 41 42 43 44
	 */
	public $id;
	/**
	 * @var Module $module the module that this controller belongs to.
	 */
	public $module;
Qiang Xue committed
45
	/**
Qiang Xue committed
46 47
	 * @var string the ID of the action that is used when the action ID is not specified
	 * in the request. Defaults to 'index'.
Qiang Xue committed
48 49
	 */
	public $defaultAction = 'index';
Qiang Xue committed
50
	/**
Qiang Xue committed
51 52 53 54 55 56 57 58 59 60 61
	 * @var string|boolean the name of the layout to be applied to this controller's views.
	 * This property mainly affects the behavior of [[render()]].
	 * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
	 * If false, no layout will be applied.
	 */
	public $layout;
	/**
	 * @var Action the action that is currently being executed. This property will be set
	 * by [[run()]] when it is called by [[Application]] to run an action.
	 */
	public $action;
Qiang Xue committed
62 63 64 65 66
	/**
	 * @var View the view object that can be used to render views or view files.
	 */
	private $_view;

Qiang Xue committed
67 68

	/**
69
	 * @param string $id the ID of this controller.
Qiang Xue committed
70
	 * @param Module $module the module that this controller belongs to.
71
	 * @param array $config name-value pairs that will be used to initialize the object properties.
Qiang Xue committed
72
	 */
Alexander Makarov committed
73
	public function __construct($id, $module, $config = [])
Qiang Xue committed
74 75 76 77 78 79 80 81 82 83
	{
		$this->id = $id;
		$this->module = $module;
		parent::__construct($config);
	}

	/**
	 * Declares external actions for the controller.
	 * This method is meant to be overwritten to declare external actions for the controller.
	 * It should return an array, with array keys being action IDs, and array values the corresponding
Qiang Xue committed
84 85 86
	 * action class names or action configuration arrays. For example,
	 *
	 * ~~~
Alexander Makarov committed
87
	 * return [
88
	 *     'action1' => 'app\components\Action1',
Alexander Makarov committed
89
	 *     'action2' => [
90
	 *         'class' => 'app\components\Action2',
Qiang Xue committed
91 92
	 *         'property1' => 'value1',
	 *         'property2' => 'value2',
Alexander Makarov committed
93 94
	 *     ],
	 * ];
Qiang Xue committed
95 96
	 * ~~~
	 *
Qiang Xue committed
97
	 * [[\Yii::createObject()]] will be used later to create the requested action
Qiang Xue committed
98
	 * using the configuration provided here.
99
	 */
Qiang Xue committed
100
	public function actions()
Qiang Xue committed
101
	{
Alexander Makarov committed
102
		return [];
Qiang Xue committed
103 104 105
	}

	/**
Qiang Xue committed
106
	 * Runs an action within this controller with the specified action ID and parameters.
Qiang Xue committed
107 108
	 * If the action ID is empty, the method will use [[defaultAction]].
	 * @param string $id the ID of the action to be executed.
Qiang Xue committed
109
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
110
	 * @return mixed the result of the action.
Qiang Xue committed
111
	 * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
112
	 * @see createAction()
Qiang Xue committed
113
	 */
Alexander Makarov committed
114
	public function runAction($id, $params = [])
Qiang Xue committed
115
	{
Qiang Xue committed
116 117
		$action = $this->createAction($id);
		if ($action !== null) {
Qiang Xue committed
118
			Yii::trace("Route to run: " . $action->getUniqueId(), __METHOD__);
Qiang Xue committed
119 120 121
			if (Yii::$app->requestedAction === null) {
				Yii::$app->requestedAction = $action;
			}
Qiang Xue committed
122 123
			$oldAction = $this->action;
			$this->action = $action;
124
			$result = null;
Qiang Xue committed
125
			$event = new ActionEvent($action);
126
			Yii::$app->trigger(Application::EVENT_BEFORE_ACTION, $event);
Qiang Xue committed
127 128 129
			if ($event->isValid && $this->module->beforeAction($action) && $this->beforeAction($action)) {
				$result = $action->runWithParams($params);
				$this->afterAction($action, $result);
130
				$this->module->afterAction($action, $result);
Qiang Xue committed
131 132 133
				$event = new ActionEvent($action);
				$event->result = &$result;
				Yii::$app->trigger(Application::EVENT_AFTER_ACTION, $event);
Qiang Xue committed
134
			}
Qiang Xue committed
135
			$this->action = $oldAction;
136
			return $result;
Qiang Xue committed
137
		} else {
Qiang Xue committed
138
			throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
Qiang Xue committed
139
		}
Qiang Xue committed
140
	}
Qiang Xue committed
141

Qiang Xue committed
142 143 144 145 146 147 148
	/**
	 * Runs a request specified in terms of a route.
	 * The route can be either an ID of an action within this controller or a complete route consisting
	 * of module IDs, controller ID and action ID. If the route starts with a slash '/', the parsing of
	 * the route will start from the application; otherwise, it will start from the parent module of this controller.
	 * @param string $route the route to be handled, e.g., 'view', 'comment/view', '/admin/comment/view'.
	 * @param array $params the parameters to be passed to the action.
149
	 * @return mixed the result of the action.
150
	 * @see runAction()
Qiang Xue committed
151
	 */
Alexander Makarov committed
152
	public function run($route, $params = [])
Qiang Xue committed
153 154 155 156 157 158 159
	{
		$pos = strpos($route, '/');
		if ($pos === false) {
			return $this->runAction($route, $params);
		} elseif ($pos > 0) {
			return $this->module->runAction($route, $params);
		} else {
Qiang Xue committed
160
			return Yii::$app->runAction(ltrim($route, '/'), $params);
Qiang Xue committed
161 162
		}
	}
Qiang Xue committed
163

Qiang Xue committed
164 165 166
	/**
	 * Binds the parameters to the action.
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
167 168
	 * @param Action $action the action to be bound with parameters.
	 * @param array $params the parameters to be bound to the action.
Qiang Xue committed
169 170 171 172
	 * @return array the valid parameters that the action can run with.
	 */
	public function bindActionParams($action, $params)
	{
Alexander Makarov committed
173
		return [];
Qiang Xue committed
174 175
	}

Qiang Xue committed
176
	/**
Qiang Xue committed
177 178 179 180 181 182
	 * Creates an action based on the given action ID.
	 * The method first checks if the action ID has been declared in [[actions()]]. If so,
	 * it will use the configuration declared there to create the action object.
	 * If not, it will look for a controller method whose name is in the format of `actionXyz`
	 * where `Xyz` stands for the action ID. If found, an [[InlineAction]] representing that
	 * method will be created and returned.
183
	 * @param string $id the action ID.
Qiang Xue committed
184
	 * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
Qiang Xue committed
185
	 */
Qiang Xue committed
186
	public function createAction($id)
Qiang Xue committed
187
	{
Qiang Xue committed
188 189 190 191
		if ($id === '') {
			$id = $this->defaultAction;
		}

Qiang Xue committed
192 193 194
		$actionMap = $this->actions();
		if (isset($actionMap[$id])) {
			return Yii::createObject($actionMap[$id], $id, $this);
195
		} elseif (preg_match('/^[a-z0-9\\-_]+$/', $id) && strpos($id, '--') === false && trim($id, '-') === $id) {
196
			$methodName = 'action' . str_replace(' ', '', ucwords(implode(' ', explode('-', $id))));
Qiang Xue committed
197 198 199
			if (method_exists($this, $methodName)) {
				$method = new \ReflectionMethod($this, $methodName);
				if ($method->getName() === $methodName) {
Qiang Xue committed
200
					return new InlineAction($id, $this, $methodName);
Qiang Xue committed
201 202
				}
			}
Qiang Xue committed
203
		}
Qiang Xue committed
204 205 206 207
		return null;
	}

	/**
208
	 * This method is invoked right before an action is to be executed (after all possible filters).
Qiang Xue committed
209
	 * You may override this method to do last-minute preparation for the action.
210
	 * If you override this method, please make sure you call the parent implementation first.
Qiang Xue committed
211 212 213 214 215
	 * @param Action $action the action to be executed.
	 * @return boolean whether the action should continue to be executed.
	 */
	public function beforeAction($action)
	{
216 217 218
		$event = new ActionEvent($action);
		$this->trigger(self::EVENT_BEFORE_ACTION, $event);
		return $event->isValid;
Qiang Xue committed
219 220 221 222 223
	}

	/**
	 * This method is invoked right after an action is executed.
	 * You may override this method to do some postprocessing for the action.
224
	 * If you override this method, please make sure you call the parent implementation first.
Qiang Xue committed
225
	 * @param Action $action the action just executed.
226
	 * @param mixed $result the action return result.
Qiang Xue committed
227
	 */
228
	public function afterAction($action, &$result)
Qiang Xue committed
229
	{
230
		$event = new ActionEvent($action);
231
		$event->result = &$result;
232
		$this->trigger(self::EVENT_AFTER_ACTION, $event);
Qiang Xue committed
233 234
	}

Qiang Xue committed
235 236 237 238 239
	/**
	 * @return string the controller ID that is prefixed with the module ID (if any).
	 */
	public function getUniqueId()
	{
Qiang Xue committed
240
		return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
Qiang Xue committed
241 242 243
	}

	/**
Qiang Xue committed
244
	 * Returns the route of the current request.
Qiang Xue committed
245 246 247 248
	 * @return string the route (module ID, controller ID and action ID) of the current request.
	 */
	public function getRoute()
	{
Qiang Xue committed
249
		return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
Qiang Xue committed
250 251
	}

Qiang Xue committed
252 253
	/**
	 * Renders a view and applies layout if available.
Qiang Xue committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
	 *
	 * The view to be rendered can be specified in one of the following formats:
	 *
	 * - path alias (e.g. "@app/views/site/index");
	 * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
	 *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
	 * - absolute path within module (e.g. "/site/index"): the view name starts with a single slash.
	 *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
	 * - relative path (e.g. "index"): the actual view file will be looked for under [[viewPath]].
	 *
	 * To determine which layout should be applied, the following two steps are conducted:
	 *
	 * 1. In the first step, it determines the layout name and the context module:
	 *
	 * - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
	 * - If [[layout]] is null, search through all ancestor modules of this controller and find the first
	 *   module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
	 *   are used as the layout name and the context module, respectively. If such a module is not found
	 *   or the corresponding layout is not a string, it will return false, meaning no applicable layout.
	 *
	 * 2. In the second step, it determines the actual layout file according to the previously found layout name
275
	 *    and context module. The layout name can be:
Qiang Xue committed
276 277 278 279 280
	 *
	 * - a path alias (e.g. "@app/views/layouts/main");
	 * - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
	 *   looked for under the [[Application::layoutPath|layout path]] of the application;
	 * - a relative path (e.g. "main"): the actual layout layout file will be looked for under the
Qiang Xue committed
281
	 *   [[Module::layoutPath|layout path]] of the context module.
Qiang Xue committed
282 283 284
	 *
	 * If the layout name does not contain a file extension, it will use the default one `.php`.
	 *
Qiang Xue committed
285 286 287 288 289
	 * @param string $view the view name. Please refer to [[findViewFile()]] on how to specify a view name.
	 * @param array $params the parameters (name-value pairs) that should be made available in the view.
	 * These parameters will not be available in the layout.
	 * @return string the rendering result.
	 * @throws InvalidParamException if the view file or the layout file does not exist.
Qiang Xue committed
290
	 */
Alexander Makarov committed
291
	public function render($view, $params = [])
Qiang Xue committed
292
	{
293
		$output = $this->getView()->render($view, $params, $this);
294
		$layoutFile = $this->findLayoutFile($this->getView());
Qiang Xue committed
295
		if ($layoutFile !== false) {
Alexander Makarov committed
296
			return $this->getView()->renderFile($layoutFile, ['content' => $output], $this);
Qiang Xue committed
297 298 299
		} else {
			return $output;
		}
Qiang Xue committed
300 301
	}

Qiang Xue committed
302 303 304
	/**
	 * Renders a view.
	 * This method differs from [[render()]] in that it does not apply any layout.
Qiang Xue committed
305
	 * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
Qiang Xue committed
306 307 308 309
	 * @param array $params the parameters (name-value pairs) that should be made available in the view.
	 * @return string the rendering result.
	 * @throws InvalidParamException if the view file does not exist.
	 */
Alexander Makarov committed
310
	public function renderPartial($view, $params = [])
Qiang Xue committed
311
	{
312
		return $this->getView()->render($view, $params, $this);
Qiang Xue committed
313 314
	}

Qiang Xue committed
315 316 317 318 319 320 321
	/**
	 * Renders a view file.
	 * @param string $file the view file to be rendered. This can be either a file path or a path alias.
	 * @param array $params the parameters (name-value pairs) that should be made available in the view.
	 * @return string the rendering result.
	 * @throws InvalidParamException if the view file does not exist.
	 */
Alexander Makarov committed
322
	public function renderFile($file, $params = [])
Qiang Xue committed
323
	{
Qiang Xue committed
324 325 326 327 328 329 330
		return $this->getView()->renderFile($file, $params, $this);
	}

	/**
	 * Returns the view object that can be used to render views or view files.
	 * The [[render()]], [[renderPartial()]] and [[renderFile()]] methods will use
	 * this view object to implement the actual view rendering.
331
	 * If not set, it will default to the "view" application component.
Qiang Xue committed
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
	 * @return View the view object that can be used to render views or view files.
	 */
	public function getView()
	{
		if ($this->_view === null) {
			$this->_view = Yii::$app->getView();
		}
		return $this->_view;
	}

	/**
	 * Sets the view object to be used by this controller.
	 * @param View $view the view object that can be used to render views or view files.
	 */
	public function setView($view)
	{
		$this->_view = $view;
Qiang Xue committed
349
	}
Qiang Xue committed
350 351 352 353 354 355 356 357 358 359 360

	/**
	 * Returns the directory containing view files for this controller.
	 * The default implementation returns the directory named as controller [[id]] under the [[module]]'s
	 * [[viewPath]] directory.
	 * @return string the directory containing the view files for this controller.
	 */
	public function getViewPath()
	{
		return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
	}
Qiang Xue committed
361

Qiang Xue committed
362 363 364 365 366 367
	/**
	 * Finds the view file based on the given view name.
	 * @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
	 * on how to specify this parameter.
	 * @return string the view file path. Note that the file may not exist.
	 */
368
	public function findViewFile($view)
Qiang Xue committed
369
	{
370
		return $this->getViewPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
371 372
	}

Qiang Xue committed
373 374
	/**
	 * Finds the applicable layout file.
375
	 * @param View $view the view object to render the layout file.
Qiang Xue committed
376
	 * @return string|boolean the layout file path, or false if layout is not needed.
Qiang Xue committed
377
	 * Please refer to [[render()]] on how to specify this parameter.
378
	 * @throws InvalidParamException if an invalid path alias is used to specify the layout.
Qiang Xue committed
379
	 */
380
	protected function findLayoutFile($view)
Qiang Xue committed
381
	{
Qiang Xue committed
382
		$module = $this->module;
Qiang Xue committed
383
		if (is_string($this->layout)) {
384
			$layout = $this->layout;
Qiang Xue committed
385 386 387 388 389
		} elseif ($this->layout === null) {
			while ($module !== null && $module->layout === null) {
				$module = $module->module;
			}
			if ($module !== null && is_string($module->layout)) {
390
				$layout = $module->layout;
Qiang Xue committed
391 392 393
			}
		}

394
		if (!isset($layout)) {
Qiang Xue committed
395 396 397
			return false;
		}

398 399 400
		if (strncmp($layout, '@', 1) === 0) {
			$file = Yii::getAlias($layout);
		} elseif (strncmp($layout, '/', 1) === 0) {
401
			$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
Qiang Xue committed
402
		} else {
403
			$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
Qiang Xue committed
404 405
		}

406 407
		if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
			return $file;
Qiang Xue committed
408
		}
409 410 411 412 413
		$path = $file . '.' . $view->defaultExtension;
		if ($view->defaultExtension !== 'php' && !is_file($path)) {
			$path = $file . '.php';
		}
		return $path;
Qiang Xue committed
414
	}
Qiang Xue committed
415
}