Controller.php 17.8 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
use Yii;
Qiang Xue committed
11
use yii\helpers\StringHelper;
Qiang Xue committed
12

Qiang Xue committed
13
/**
Qiang Xue committed
14
 * Controller is the base class for classes containing controller logic.
Qiang Xue committed
15 16 17 18
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
19
class Controller extends Component
Qiang Xue committed
20
{
21 22 23 24
	/**
	 * @event ActionEvent an event raised right before executing a controller action.
	 * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
	 */
Qiang Xue committed
25
	const EVENT_BEFORE_ACTION = 'beforeAction';
26 27 28
	/**
	 * @event ActionEvent an event raised right after executing a controller action.
	 */
Qiang Xue committed
29 30
	const EVENT_AFTER_ACTION = 'afterAction';

Qiang Xue committed
31
	/**
Qiang Xue committed
32
	 * @var string the ID of this controller
Qiang Xue committed
33 34 35 36 37 38
	 */
	public $id;
	/**
	 * @var Module $module the module that this controller belongs to.
	 */
	public $module;
Qiang Xue committed
39
	/**
Qiang Xue committed
40 41
	 * @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
42 43
	 */
	public $defaultAction = 'index';
Qiang Xue committed
44
	/**
Qiang Xue committed
45 46 47 48 49 50 51 52 53 54 55
	 * @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
56 57 58 59 60
	/**
	 * @var View the view object that can be used to render views or view files.
	 */
	private $_view;

Qiang Xue committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

	/**
	 * @param string $id the ID of this controller
	 * @param Module $module the module that this controller belongs to.
	 * @param array $config name-value pairs that will be used to initialize the object properties
	 */
	public function __construct($id, $module, $config = array())
	{
		$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
78 79 80 81
	 * action class names or action configuration arrays. For example,
	 *
	 * ~~~
	 * return array(
Qiang Xue committed
82
	 *     'action1' => '@app/components/Action1',
Qiang Xue committed
83
	 *     'action2' => array(
Qiang Xue committed
84
	 *         'class' => '@app/components/Action2',
Qiang Xue committed
85 86 87 88 89 90
	 *         'property1' => 'value1',
	 *         'property2' => 'value2',
	 *     ),
	 * );
	 * ~~~
	 *
Qiang Xue committed
91
	 * [[\Yii::createObject()]] will be used later to create the requested action
Qiang Xue committed
92
	 * using the configuration provided here.
93
	 */
Qiang Xue committed
94
	public function actions()
Qiang Xue committed
95
	{
Qiang Xue committed
96
		return array();
Qiang Xue committed
97 98 99
	}

	/**
Qiang Xue committed
100 101 102
	 * Runs an action with the specified action ID and parameters.
	 * 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
103
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
Qiang Xue committed
104 105
	 * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
	 * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
Qiang Xue committed
106
	 * @see createAction
Qiang Xue committed
107
	 */
Qiang Xue committed
108
	public function runAction($id, $params = array())
Qiang Xue committed
109
	{
Qiang Xue committed
110 111 112 113
		$action = $this->createAction($id);
		if ($action !== null) {
			$oldAction = $this->action;
			$this->action = $action;
114 115 116 117 118 119 120
			$status = 1;
			if ($this->module->beforeAction($action)) {
				if ($this->beforeAction($action)) {
					$status = $action->runWithParams($params);
					$this->afterAction($action);
				}
				$this->module->afterAction($action);
Qiang Xue committed
121
			}
Qiang Xue committed
122 123
			$this->action = $oldAction;
			return $status;
Qiang Xue committed
124
		} else {
Qiang Xue committed
125
			throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
Qiang Xue committed
126
		}
Qiang Xue committed
127
	}
Qiang Xue committed
128

Qiang Xue committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	/**
	 * 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.
	 * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
	 * @see runAction
	 * @see forward
	 */
	public function run($route, $params = array())
	{
		$pos = strpos($route, '/');
		if ($pos === false) {
			return $this->runAction($route, $params);
		} elseif ($pos > 0) {
			return $this->module->runAction($route, $params);
		} else {
Qiang Xue committed
148
			return Yii::$app->runAction(ltrim($route, '/'), $params);
Qiang Xue committed
149 150
		}
	}
Qiang Xue committed
151

Qiang Xue committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	/**
	 * Binds the parameters to the action.
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
	 * This method will check the parameter names that the action requires and return
	 * the provided parameters according to the requirement. If there is any missing parameter,
	 * an exception will be thrown.
	 * @param Action $action the action to be bound with parameters
	 * @param array $params the parameters to be bound to the action
	 * @return array the valid parameters that the action can run with.
	 * @throws InvalidRequestException if there are missing parameters.
	 */
	public function bindActionParams($action, $params)
	{
		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

		$args = array();
		$missing = array();
		foreach ($method->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($name, $params)) {
				$args[] = $params[$name];
				unset($params[$name]);
			} elseif ($param->isDefaultValueAvailable()) {
				$args[] = $param->getDefaultValue();
			} else {
				$missing[] = $name;
			}
		}

185
		if (!empty($missing)) {
186
			throw new InvalidRequestException(Yii::t('yii|Missing required parameters: {params}', array(
Qiang Xue committed
187 188 189 190 191 192 193
				'{params}' => implode(', ', $missing),
			)));
		}

		return $args;
	}

Qiang Xue committed
194 195 196 197 198 199 200 201 202 203 204 205
	/**
	 * Forwards the current execution flow to handle a new request specified by a route.
	 * The only difference between this method and [[run()]] is that after calling this method,
	 * the application will exit.
	 * @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.
	 * @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
	 * @see run
	 */
	public function forward($route, $params = array())
	{
		$status = $this->run($route, $params);
Qiang Xue committed
206
		Yii::$app->end($status);
Qiang Xue committed
207 208 209
	}

	/**
Qiang Xue committed
210 211 212 213 214 215 216 217
	 * 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.
	 * @param string $id the action ID
	 * @return Action the newly created action instance. Null if the ID doesn't resolve into any action.
Qiang Xue committed
218
	 */
Qiang Xue committed
219
	public function createAction($id)
Qiang Xue committed
220
	{
Qiang Xue committed
221 222 223 224
		if ($id === '') {
			$id = $this->defaultAction;
		}

Qiang Xue committed
225 226 227 228 229 230 231 232
		$actionMap = $this->actions();
		if (isset($actionMap[$id])) {
			return Yii::createObject($actionMap[$id], $id, $this);
		} elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) {
			$methodName = 'action' . StringHelper::id2camel($id);
			if (method_exists($this, $methodName)) {
				$method = new \ReflectionMethod($this, $methodName);
				if ($method->getName() === $methodName) {
Qiang Xue committed
233
					return new InlineAction($id, $this, $methodName);
Qiang Xue committed
234 235
				}
			}
Qiang Xue committed
236
		}
Qiang Xue committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
		return null;
	}

	/**
	 * This method is invoked right before an action is to be executed (after all possible filters.)
	 * You may override this method to do last-minute preparation for the action.
	 * @param Action $action the action to be executed.
	 * @return boolean whether the action should continue to be executed.
	 */
	public function beforeAction($action)
	{
		$event = new ActionEvent($action);
		$this->trigger(self::EVENT_BEFORE_ACTION, $event);
		return $event->isValid;
	}

	/**
	 * This method is invoked right after an action is executed.
	 * You may override this method to do some postprocessing for the action.
	 * @param Action $action the action just executed.
	 */
	public function afterAction($action)
	{
		$this->trigger(self::EVENT_AFTER_ACTION, new ActionEvent($action));
Qiang Xue committed
261 262 263 264 265 266 267 268 269 270 271 272
	}

	/**
	 * Returns the request parameters that will be used for action parameter binding.
	 * Default implementation simply returns an empty array.
	 * Child classes may override this method to customize the parameters to be provided
	 * for action parameter binding (e.g. `$_GET`).
	 * @return array the request parameters (name-value pairs) to be used for action parameter binding
	 */
	public function getActionParams()
	{
		return array();
Qiang Xue committed
273 274 275
	}

	/**
Qiang Xue committed
276 277 278 279 280
	 * Validates the parameter being bound to actions.
	 * This method is invoked when parameters are being bound to the currently requested action.
	 * Child classes may override this method to throw exceptions when there are missing and/or unknown parameters.
	 * @param Action $action the currently requested action
	 * @param array $missingParams the names of the missing parameters
resurtm committed
281
	 * @param array $unknownParams the unknown parameters (name => value)
Qiang Xue committed
282
	 */
Qiang Xue committed
283
	public function validateActionParams($action, $missingParams, $unknownParams)
Qiang Xue committed
284 285 286 287 288 289 290 291
	{
	}

	/**
	 * @return string the controller ID that is prefixed with the module ID (if any).
	 */
	public function getUniqueId()
	{
Qiang Xue committed
292
		return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
Qiang Xue committed
293 294 295
	}

	/**
Qiang Xue committed
296
	 * Returns the route of the current request.
Qiang Xue committed
297 298 299 300
	 * @return string the route (module ID, controller ID and action ID) of the current request.
	 */
	public function getRoute()
	{
Qiang Xue committed
301
		return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
Qiang Xue committed
302 303
	}

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	/**
	 * Populates one or multiple models from the given data array.
	 * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array.
	 * @param Model $model the model to be populated. If there are more than one model to be populated,
	 * you may supply them as additional parameters.
	 * @return boolean whether at least one model is successfully populated with the data.
	 */
	public function populate($data, $model)
	{
		$success = false;
		if (!empty($data) && is_array($data)) {
			$models = func_get_args();
			array_shift($models);
			foreach ($models as $model) {
				/** @var Model $model */
				$scope = $model->formName();
				if ($scope == '') {
321
					$model->setAttributes($data);
322 323
					$success = true;
				} elseif (isset($data[$scope])) {
324
					$model->setAttributes($data[$scope]);
325 326 327 328 329 330 331
					$success = true;
				}
			}
		}
		return $success;
	}

Qiang Xue committed
332 333
	/**
	 * Renders a view and applies layout if available.
Qiang Xue committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
	 *
	 * 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
	 *    and context module. The layout name can be
	 *
	 * - 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
	 *   [[Module::viewPath|view path]] of the context module.
	 *
	 * If the layout name does not contain a file extension, it will use the default one `.php`.
	 *
Qiang Xue committed
365 366 367 368 369
	 * @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
370
	 */
Qiang Xue committed
371 372
	public function render($view, $params = array())
	{
Qiang Xue committed
373 374
		$viewFile = $this->findViewFile($view);
		$output = $this->getView()->renderFile($viewFile, $params, $this);
Qiang Xue committed
375
		$layoutFile = $this->findLayoutFile();
Qiang Xue committed
376
		if ($layoutFile !== false) {
Qiang Xue committed
377
			return $this->getView()->renderFile($layoutFile, array('content' => $output), $this);
Qiang Xue committed
378 379 380
		} else {
			return $output;
		}
Qiang Xue committed
381 382
	}

Qiang Xue committed
383 384 385
	/**
	 * Renders a view.
	 * This method differs from [[render()]] in that it does not apply any layout.
Qiang Xue committed
386
	 * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
Qiang Xue committed
387 388 389 390
	 * @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.
	 */
Qiang Xue committed
391 392
	public function renderPartial($view, $params = array())
	{
Qiang Xue committed
393 394
		$viewFile = $this->findViewFile($view);
		return $this->getView()->renderFile($viewFile, $params, $this);
Qiang Xue committed
395 396
	}

Qiang Xue committed
397 398 399 400 401 402 403
	/**
	 * 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.
	 */
Qiang Xue committed
404 405
	public function renderFile($file, $params = array())
	{
Qiang Xue committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
		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.
	 * @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
430
	}
Qiang Xue committed
431 432 433 434 435 436 437 438 439 440 441

	/**
	 * 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
442

Qiang Xue committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
	/**
	 * 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.
	 */
	protected function findViewFile($view)
	{
		if (strncmp($view, '@', 1) === 0) {
			// e.g. "@app/views/main"
			$file = Yii::getAlias($view);
		} elseif (strncmp($view, '//', 2) === 0) {
			// e.g. "//layouts/main"
			$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
		} elseif (strncmp($view, '/', 1) === 0) {
			// e.g. "/site/index"
			$file = $this->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
		} else {
			$file = $this->getViewPath() . DIRECTORY_SEPARATOR . $view;
		}

Qiang Xue committed
464
		return pathinfo($file, PATHINFO_EXTENSION) === '' ? $file . '.php' : $file;
Qiang Xue committed
465 466
	}

Qiang Xue committed
467 468 469
	/**
	 * Finds the applicable layout file.
	 * @return string|boolean the layout file path, or false if layout is not needed.
Qiang Xue committed
470
	 * Please refer to [[render()]] on how to specify this parameter.
Qiang Xue committed
471 472 473 474
	 * @throws InvalidParamException if an invalid path alias is used to specify the layout
	 */
	protected function findLayoutFile()
	{
Qiang Xue committed
475
		$module = $this->module;
Qiang Xue committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
		if (is_string($this->layout)) {
			$view = $this->layout;
		} elseif ($this->layout === null) {
			while ($module !== null && $module->layout === null) {
				$module = $module->module;
			}
			if ($module !== null && is_string($module->layout)) {
				$view = $module->layout;
			}
		}

		if (!isset($view)) {
			return false;
		}

		if (strncmp($view, '@', 1) === 0) {
			$file = Yii::getAlias($view);
		} elseif (strncmp($view, '/', 1) === 0) {
			$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
		} else {
			$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
		}

Qiang Xue committed
499
		if (pathinfo($file, PATHINFO_EXTENSION) === '') {
Qiang Xue committed
500 501 502 503
			$file .= '.php';
		}
		return $file;
	}
Qiang Xue committed
504
}