Controller.php 9.67 KB
Newer Older
Qiang Xue committed
1 2 3 4 5
<?php
/**
 * Controller class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9 10 11 12
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

/**
Qiang Xue committed
13
 * Controller is the base class for classes containing controller logic.
Qiang Xue committed
14
 *
Qiang Xue committed
15
 * Controller implements the action life cycles, which consist of the following steps:
Qiang Xue committed
16
 *
Qiang Xue committed
17 18
 * 1. [[authorize]]
 * 2. [[beforeAction]]
Qiang Xue committed
19
 * 3. [[afterAction]]
Qiang Xue committed
20
 *
Qiang Xue committed
21 22 23
 * @property array $actionParams the request parameters (name-value pairs) to be used for action parameter binding
 * @property string $route the route (module ID, controller ID and action ID) of the current request.
 * @property string $uniqueId the controller ID that is prefixed with the module ID (if any).
Qiang Xue committed
24 25 26 27
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
28
class Controller extends Component
Qiang Xue committed
29
{
Qiang Xue committed
30 31 32 33 34 35 36 37
	/**
	 * @var string ID of this controller
	 */
	public $id;
	/**
	 * @var Module $module the module that this controller belongs to.
	 */
	public $module;
Qiang Xue committed
38 39 40 41
	/**
	 * @var string the name of the default action. Defaults to 'index'.
	 */
	public $defaultAction = 'index';
Qiang Xue committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	/**
	 * @var array mapping from action ID to action configuration.
	 * Array keys are action IDs, and array values are the corresponding
	 * action class names or action configuration arrays. For example,
	 *
	 * ~~~
	 * return array(
	 *     'action1' => '@application/components/Action1',
	 *     'action2' => array(
	 *         'class' => '@application/components/Action2',
	 *         'property1' => 'value1',
	 *         'property2' => 'value2',
	 *     ),
	 * );
	 * ~~~
	 *
	 * [[\Yii::createObject()]] will be invoked to create the requested action
	 * using the configuration provided here.
	 *
	 * Note, in order to inherit actions defined in the parent class, a child class needs to
	 * merge the parent actions with child actions using functions like `array_merge()`.
	 * @see createAction
	 */
	public $actions = array();
66 67 68 69
	/**
	 * @var Action the action that is currently being executed
	 */
	public $action;
Qiang Xue committed
70
	/**
Qiang Xue committed
71 72 73 74
	 * @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 layout specified by the [[module]] should be used.
	 * If false, no layout will be applied.
Qiang Xue committed
75
	 */
Qiang Xue committed
76
	public $layout;
Qiang Xue committed
77 78

	/**
Qiang Xue committed
79 80
	 * @param string $id ID of this controller
	 * @param Module $module the module that this controller belongs to.
Qiang Xue committed
81
	 * @param array $config name-value pairs that will be used to initialize the object properties
Qiang Xue committed
82
	 */
Qiang Xue committed
83
	public function __construct($id, $module, $config = array())
Qiang Xue committed
84
	{
Qiang Xue committed
85 86
		$this->id = $id;
		$this->module = $module;
Qiang Xue committed
87
		parent::__construct($config);
Qiang Xue committed
88 89 90 91
	}

	/**
	 * Initializes the controller.
Qiang Xue committed
92
	 * This method is called by the application before the controller starts to execute an action.
Qiang Xue committed
93 94 95 96 97 98 99
	 * You may override this method to perform the needed initialization for the controller.
	 */
	public function init()
	{
	}

	/**
Qiang Xue committed
100 101 102
	 * Runs the controller with the specified action and parameters.
	 * @param Action|string $action the action to be executed. This can be either an action object
	 * or the ID of the action.
Qiang Xue committed
103
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
Qiang Xue committed
104
	 * If null, the result of [[getActionParams()]] will be used as action parameters.
Qiang Xue committed
105 106
	 * @return integer the exit status of the action. 0 means normal, other values mean abnormal.
	 * @see missingAction
Qiang Xue committed
107
	 * @see createAction
Qiang Xue committed
108
	 */
Qiang Xue committed
109
	public function run($action, $params = null)
Qiang Xue committed
110
	{
Qiang Xue committed
111 112 113 114 115 116 117
		if (is_string($action)) {
			if (($a = $this->createAction($action)) !== null) {
				$action = $a;
			} else {
				$this->missingAction($action);
				return 1;
			}
Qiang Xue committed
118 119
		}

120 121
		$priorAction = $this->action;
		$this->action = $action;
Qiang Xue committed
122 123

		if ($this->authorize($action) && $this->beforeAction($action)) {
Qiang Xue committed
124 125 126 127
			if ($params === null) {
				$params = $this->getActionParams();
			}
			$status = $action->runWithParams($params);
Qiang Xue committed
128 129 130
			$this->afterAction($action);
		} else {
			$status = 1;
Qiang Xue committed
131
		}
Qiang Xue committed
132

133
		$this->action = $priorAction;
Qiang Xue committed
134

Qiang Xue committed
135
		return $status;
Qiang Xue committed
136 137 138
	}

	/**
Qiang Xue committed
139
	 * Creates the action instance based on the action ID.
Qiang Xue committed
140
	 * The action can be either an inline action or an object.
Qiang Xue committed
141 142
	 * The latter is created by looking up the action map specified in [[actions]].
	 * @param string $actionID ID of the action. If empty, it will take the value of [[defaultAction]].
Qiang Xue committed
143
	 * @return Action the action instance, null if the action does not exist.
Qiang Xue committed
144 145 146 147 148 149 150
	 * @see actions
	 */
	public function createAction($actionID)
	{
		if ($actionID === '') {
			$actionID = $this->defaultAction;
		}
Qiang Xue committed
151 152 153
		if (isset($this->actions[$actionID])) {
			return \Yii::createObject($this->actions[$actionID], $actionID, $this);
		} elseif (method_exists($this, 'action' . $actionID)) {
Qiang Xue committed
154 155
			return new InlineAction($actionID, $this);
		} else {
Qiang Xue committed
156
			return null;
Qiang Xue committed
157
		}
Qiang Xue committed
158 159 160 161 162 163 164 165 166 167 168 169
	}

	/**
	 * 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
170 171 172
	}

	/**
Qiang Xue committed
173 174 175
	 * This method is invoked when the request parameters do not satisfy the requirement of the specified action.
	 * The default implementation will throw an exception.
	 * @param Action $action the action being executed
Qiang Xue committed
176
	 * @param Exception $exception the exception about the invalid parameters
Qiang Xue committed
177
	 * @throws Exception whenever this method is invoked
Qiang Xue committed
178
	 */
Qiang Xue committed
179
	public function invalidActionParams($action, $exception)
Qiang Xue committed
180
	{
Qiang Xue committed
181
		throw $exception;
Qiang Xue committed
182 183
	}

Qiang Xue committed
184 185 186 187 188 189 190 191 192 193 194
	/**
	 * This method is invoked when extra parameters are provided to an action when it is executed.
	 * The default implementation does nothing.
	 * @param Action $action the action being executed
	 * @param array $expected the expected action parameters (name => value)
	 * @param array $actual the actual action parameters (name => value)
	 */
	public function extraActionParams($action, $expected, $actual)
	{
	}

Qiang Xue committed
195 196 197 198 199
	/**
	 * Handles the request whose action is not recognized.
	 * This method is invoked when the controller cannot find the requested action.
	 * The default implementation simply throws an exception.
	 * @param string $actionID the missing action name
Qiang Xue committed
200
	 * @throws BadRequestException whenever this method is invoked
Qiang Xue committed
201 202 203
	 */
	public function missingAction($actionID)
	{
Qiang Xue committed
204
		throw new BadRequestException(\Yii::t('yii', 'The system is unable to find the requested action "{action}".',
Qiang Xue committed
205 206 207 208 209 210 211 212
			array('{action}' => $actionID == '' ? $this->defaultAction : $actionID)));
	}

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

	/**
Qiang Xue committed
217
	 * Returns the route of the current request.
Qiang Xue committed
218 219 220 221
	 * @return string the route (module ID, controller ID and action ID) of the current request.
	 */
	public function getRoute()
	{
Qiang Xue committed
222
		return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId();
Qiang Xue committed
223 224 225 226 227
	}

	/**
	 * Processes the request using another controller action.
	 * @param string $route the route of the new controller action. This can be an action ID, or a complete route
Qiang Xue committed
228 229
	 * with module ID (optional in the current module), controller ID and action ID. If the former,
	 * the action is assumed to be located within the current controller.
Qiang Xue committed
230 231 232 233
	 * @param array $params the parameters to be passed to the action.
	 * If null, the result of [[getActionParams()]] will be used as action parameters.
	 * Note that the parameters must be name-value pairs with the names corresponding to
	 * the parameter names as declared by the action.
Qiang Xue committed
234 235
	 * @param boolean $exit whether to end the application after this call. Defaults to true.
	 */
Qiang Xue committed
236
	public function forward($route, $params = array(), $exit = true)
Qiang Xue committed
237 238
	{
		if (strpos($route, '/') === false) {
Qiang Xue committed
239
			$status = $this->run($route, $params);
Qiang Xue committed
240 241 242
		} else {
			if ($route[0] !== '/' && !$this->module instanceof Application) {
				$route = '/' . $this->module->getUniqueId() . '/' . $route;
Qiang Xue committed
243
			}
Qiang Xue committed
244
			$status = \Yii::$application->runController($route, $params);
Qiang Xue committed
245 246
		}
		if ($exit) {
Qiang Xue committed
247
			\Yii::$application->end($status);
Qiang Xue committed
248 249 250
		}
	}

251 252 253 254 255
	/**
	 * This method is invoked when checking the access for the action to be executed.
	 * @param Action $action the action to be executed.
	 * @return boolean whether the action is allowed to be executed.
	 */
Qiang Xue committed
256
	public function authorize($action)
257 258 259 260 261 262
	{
		$event = new ActionEvent($action);
		$this->trigger(__METHOD__, $event);
		return $event->isValid;
	}

Qiang Xue committed
263 264 265
	/**
	 * 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.
Qiang Xue committed
266
	 * @param Action $action the action to be executed.
267
	 * @return boolean whether the action should continue to be executed.
Qiang Xue committed
268
	 */
Qiang Xue committed
269
	public function beforeAction($action)
Qiang Xue committed
270
	{
271 272 273
		$event = new ActionEvent($action);
		$this->trigger(__METHOD__, $event);
		return $event->isValid;
Qiang Xue committed
274 275 276 277 278
	}

	/**
	 * This method is invoked right after an action is executed.
	 * You may override this method to do some postprocessing for the action.
Qiang Xue committed
279
	 * @param Action $action the action just executed.
Qiang Xue committed
280
	 */
Qiang Xue committed
281
	public function afterAction($action)
282
	{
Qiang Xue committed
283
		$this->trigger(__METHOD__, new ActionEvent($action));
284 285
	}

Qiang Xue committed
286 287
	public function render($view, $params = array())
	{
Qiang Xue committed
288
		return $this->createView()->render($view, $params);
Qiang Xue committed
289 290 291 292
	}

	public function renderText($text)
	{
Qiang Xue committed
293
		return $this->createView()->renderText($text);
Qiang Xue committed
294 295 296 297
	}

	public function renderPartial($view, $params = array())
	{
Qiang Xue committed
298
		return $this->createView()->renderPartial($view, $params);
Qiang Xue committed
299 300
	}

Qiang Xue committed
301 302
	public function createView()
	{
Qiang Xue committed
303
		return new View($this);
Qiang Xue committed
304 305
	}
}