Controller.php 11 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
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
12 13 14
use Yii;
use yii\util\StringHelper;

Qiang Xue committed
15
/**
Qiang Xue committed
16
 * Controller is the base class for classes containing controller logic.
Qiang Xue committed
17
 *
Qiang Xue committed
18 19
 * @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
20 21 22 23
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
24
class Controller extends Component
Qiang Xue committed
25
{
Qiang Xue committed
26 27 28
	const EVENT_BEFORE_ACTION = 'beforeAction';
	const EVENT_AFTER_ACTION = 'afterAction';

Qiang Xue committed
29
	/**
Qiang Xue committed
30
	 * @var string the ID of this controller
Qiang Xue committed
31 32 33 34 35 36
	 */
	public $id;
	/**
	 * @var Module $module the module that this controller belongs to.
	 */
	public $module;
Qiang Xue committed
37
	/**
Qiang Xue committed
38 39
	 * @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
40 41
	 */
	public $defaultAction = 'index';
Qiang Xue committed
42
	/**
Qiang Xue committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	 * @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;

	/**
	 * @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
71 72 73 74 75 76 77 78 79 80 81 82 83
	 * 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',
	 *     ),
	 * );
	 * ~~~
	 *
Qiang Xue committed
84
	 * [[\Yii::createObject()]] will be used later to create the requested action
Qiang Xue committed
85
	 * using the configuration provided here.
86
	 */
Qiang Xue committed
87
	public function actions()
Qiang Xue committed
88
	{
Qiang Xue committed
89
		return array();
Qiang Xue committed
90 91 92
	}

	/**
Qiang Xue committed
93 94 95
	 * 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
96
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
Qiang Xue committed
97 98
	 * @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
99
	 * @see createAction
Qiang Xue committed
100
	 */
Qiang Xue committed
101
	public function runAction($id, $params = array())
Qiang Xue committed
102
	{
Qiang Xue committed
103 104 105 106
		$action = $this->createAction($id);
		if ($action !== null) {
			$oldAction = $this->action;
			$this->action = $action;
Qiang Xue committed
107

Qiang Xue committed
108
			if ($this->beforeAction($action)) {
Qiang Xue committed
109 110 111 112
				$status = $action->runWithParams($params);
				$this->afterAction($action);
			} else {
				$status = 1;
Qiang Xue committed
113
			}
Qiang Xue committed
114 115 116 117

			$this->action = $oldAction;

			return $status;
Qiang Xue committed
118
		} else {
Qiang Xue committed
119
			throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $id);
Qiang Xue committed
120
		}
Qiang Xue committed
121
	}
Qiang Xue committed
122

Qiang Xue committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	/**
	 * 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
142
			return \Yii::$application->runAction(ltrim($route, '/'), $params);
Qiang Xue committed
143 144
		}
	}
Qiang Xue committed
145

Qiang Xue committed
146 147 148 149 150 151 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
	/**
	 * 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;
			}
		}

		if ($missing !== array()) {
Qiang Xue committed
180
			throw new InvalidRequestException(Yii::t('yii:Missing required parameters: {params}', array(
Qiang Xue committed
181 182 183 184 185 186 187
				'{params}' => implode(', ', $missing),
			)));
		}

		return $args;
	}

Qiang Xue committed
188 189 190 191 192 193 194 195 196 197 198 199 200
	/**
	 * 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);
		exit($status);
Qiang Xue committed
201 202 203
	}

	/**
Qiang Xue committed
204 205 206 207 208 209 210 211
	 * 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
212
	 */
Qiang Xue committed
213
	public function createAction($id)
Qiang Xue committed
214
	{
Qiang Xue committed
215 216 217 218
		if ($id === '') {
			$id = $this->defaultAction;
		}

Qiang Xue committed
219 220 221 222 223 224 225 226
		$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
227
					return new InlineAction($id, $this, $methodName);
Qiang Xue committed
228 229
				}
			}
Qiang Xue committed
230
		}
Qiang Xue committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
		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
255 256 257 258 259 260 261 262 263 264 265 266
	}

	/**
	 * 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
267 268 269
	}

	/**
Qiang Xue committed
270 271 272 273 274 275
	 * 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
	 * @param array $unknownParams the unknown parameters (name=>value)
Qiang Xue committed
276
	 */
Qiang Xue committed
277
	public function validateActionParams($action, $missingParams, $unknownParams)
Qiang Xue committed
278 279 280 281 282 283 284 285
	{
	}

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

	/**
Qiang Xue committed
290
	 * Returns the route of the current request.
Qiang Xue committed
291 292 293 294
	 * @return string the route (module ID, controller ID and action ID) of the current request.
	 */
	public function getRoute()
	{
Qiang Xue committed
295
		return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
Qiang Xue committed
296 297
	}

Qiang Xue committed
298 299 300 301 302 303 304
	/**
	 * Renders a view and applies layout if available.
	 *
	 * @param $view
	 * @param array $params
	 * @return string
	 */
Qiang Xue committed
305 306
	public function render($view, $params = array())
	{
Qiang Xue committed
307
		return $this->createView()->render($view, $params);
Qiang Xue committed
308 309
	}

Qiang Xue committed
310
	public function renderContent($content)
Qiang Xue committed
311
	{
Qiang Xue committed
312
		return $this->createView()->renderContent($content);
Qiang Xue committed
313 314 315 316
	}

	public function renderPartial($view, $params = array())
	{
Qiang Xue committed
317
		return $this->createView()->renderPartial($view, $params);
Qiang Xue committed
318 319
	}

Qiang Xue committed
320 321 322 323 324
	public function renderFile($file, $params = array())
	{
		return $this->createView()->renderFile($file, $params);
	}

Qiang Xue committed
325 326
	public function createView()
	{
Qiang Xue committed
327
		return new View($this);
Qiang Xue committed
328
	}
Qiang Xue committed
329 330 331 332 333 334 335 336 337 338 339

	/**
	 * 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
340
}