Controller.php 9.42 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
	}

	/**
Qiang Xue committed
91 92 93
	 * 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
94
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
Qiang Xue committed
95
	 * If null, the result of [[getActionParams()]] will be used as action parameters.
Qiang Xue committed
96 97
	 * @return integer the exit status of the action. 0 means normal, other values mean abnormal.
	 * @see missingAction
Qiang Xue committed
98
	 * @see createAction
Qiang Xue committed
99
	 */
Qiang Xue committed
100
	public function run($action, $params = null)
Qiang Xue committed
101
	{
Qiang Xue committed
102 103 104 105 106 107 108
		if (is_string($action)) {
			if (($a = $this->createAction($action)) !== null) {
				$action = $a;
			} else {
				$this->missingAction($action);
				return 1;
			}
Qiang Xue committed
109 110
		}

111 112
		$priorAction = $this->action;
		$this->action = $action;
Qiang Xue committed
113 114

		if ($this->authorize($action) && $this->beforeAction($action)) {
Qiang Xue committed
115 116 117 118
			if ($params === null) {
				$params = $this->getActionParams();
			}
			$status = $action->runWithParams($params);
Qiang Xue committed
119 120 121
			$this->afterAction($action);
		} else {
			$status = 1;
Qiang Xue committed
122
		}
Qiang Xue committed
123

124
		$this->action = $priorAction;
Qiang Xue committed
125

Qiang Xue committed
126
		return $status;
Qiang Xue committed
127 128 129
	}

	/**
Qiang Xue committed
130
	 * Creates the action instance based on the action ID.
Qiang Xue committed
131
	 * The action can be either an inline action or an object.
Qiang Xue committed
132 133
	 * 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
134
	 * @return Action the action instance, null if the action does not exist.
Qiang Xue committed
135 136 137 138 139 140 141
	 * @see actions
	 */
	public function createAction($actionID)
	{
		if ($actionID === '') {
			$actionID = $this->defaultAction;
		}
Qiang Xue committed
142 143 144
		if (isset($this->actions[$actionID])) {
			return \Yii::createObject($this->actions[$actionID], $actionID, $this);
		} elseif (method_exists($this, 'action' . $actionID)) {
Qiang Xue committed
145 146
			return new InlineAction($actionID, $this);
		} else {
Qiang Xue committed
147
			return null;
Qiang Xue committed
148
		}
Qiang Xue committed
149 150 151 152 153 154 155 156 157 158 159 160
	}

	/**
	 * 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
161 162 163
	}

	/**
Qiang Xue committed
164 165 166
	 * 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
167
	 * @param Exception $exception the exception about the invalid parameters
Qiang Xue committed
168
	 * @throws Exception whenever this method is invoked
Qiang Xue committed
169
	 */
Qiang Xue committed
170
	public function invalidActionParams($action, $exception)
Qiang Xue committed
171
	{
Qiang Xue committed
172
		throw $exception;
Qiang Xue committed
173 174
	}

Qiang Xue committed
175 176 177 178 179 180 181 182 183 184 185
	/**
	 * 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
186 187 188 189 190
	/**
	 * 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
191
	 * @throws BadRequestException whenever this method is invoked
Qiang Xue committed
192 193 194
	 */
	public function missingAction($actionID)
	{
Qiang Xue committed
195
		throw new BadRequestException(\Yii::t('yii', 'The system is unable to find the requested action "{action}".',
Qiang Xue committed
196 197 198 199 200 201 202 203
			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
204
		return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
Qiang Xue committed
205 206 207
	}

	/**
Qiang Xue committed
208
	 * Returns the route of the current request.
Qiang Xue committed
209 210 211 212
	 * @return string the route (module ID, controller ID and action ID) of the current request.
	 */
	public function getRoute()
	{
Qiang Xue committed
213
		return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId();
Qiang Xue committed
214 215 216 217 218
	}

	/**
	 * 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
219 220
	 * 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
221 222 223 224
	 * @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
225 226
	 * @param boolean $exit whether to end the application after this call. Defaults to true.
	 */
Qiang Xue committed
227
	public function forward($route, $params = array(), $exit = true)
Qiang Xue committed
228 229
	{
		if (strpos($route, '/') === false) {
Qiang Xue committed
230
			$status = $this->run($route, $params);
Qiang Xue committed
231 232 233
		} else {
			if ($route[0] !== '/' && !$this->module instanceof Application) {
				$route = '/' . $this->module->getUniqueId() . '/' . $route;
Qiang Xue committed
234
			}
Qiang Xue committed
235
			$status = \Yii::$application->runController($route, $params);
Qiang Xue committed
236 237
		}
		if ($exit) {
Qiang Xue committed
238
			\Yii::$application->end($status);
Qiang Xue committed
239 240 241
		}
	}

242 243 244 245 246
	/**
	 * 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
247
	public function authorize($action)
248 249 250 251 252 253
	{
		$event = new ActionEvent($action);
		$this->trigger(__METHOD__, $event);
		return $event->isValid;
	}

Qiang Xue committed
254 255 256
	/**
	 * 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
257
	 * @param Action $action the action to be executed.
258
	 * @return boolean whether the action should continue to be executed.
Qiang Xue committed
259
	 */
Qiang Xue committed
260
	public function beforeAction($action)
Qiang Xue committed
261
	{
262 263 264
		$event = new ActionEvent($action);
		$this->trigger(__METHOD__, $event);
		return $event->isValid;
Qiang Xue committed
265 266 267 268 269
	}

	/**
	 * 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
270
	 * @param Action $action the action just executed.
Qiang Xue committed
271
	 */
Qiang Xue committed
272
	public function afterAction($action)
273
	{
Qiang Xue committed
274
		$this->trigger(__METHOD__, new ActionEvent($action));
275 276
	}

Qiang Xue committed
277 278
	public function render($view, $params = array())
	{
Qiang Xue committed
279
		return $this->createView()->render($view, $params);
Qiang Xue committed
280 281 282 283
	}

	public function renderText($text)
	{
Qiang Xue committed
284
		return $this->createView()->renderText($text);
Qiang Xue committed
285 286 287 288
	}

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

Qiang Xue committed
292 293
	public function createView()
	{
Qiang Xue committed
294
		return new View($this);
Qiang Xue committed
295 296
	}
}