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

Qiang Xue committed
10 11
namespace yii\base;

Qiang Xue committed
12 13
use yii\util\ReflectionHelper;

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Action is the base class for all controller action classes.
Qiang Xue committed
16
 *
Qiang Xue committed
17
 * Action provides a way to divide a complex controller into
Qiang Xue committed
18 19
 * smaller actions in separate class files.
 *
Qiang Xue committed
20 21 22
 * Derived classes must implement a method named `run()`. This method
 * will be invoked by the controller when the action is requested.
 * The `run()` method can have parameters which will be filled up
23
 * with user input values automatically according to their names.
Qiang Xue committed
24 25
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
26
 * @since 2.0
Qiang Xue committed
27
 */
Qiang Xue committed
28
class Action extends Component
Qiang Xue committed
29 30
{
	/**
Qiang Xue committed
31
	 * @var string ID of the action
Qiang Xue committed
32
	 */
Qiang Xue committed
33
	public $id;
Qiang Xue committed
34
	/**
Qiang Xue committed
35
	 * @var Controller the controller that owns this action
Qiang Xue committed
36
	 */
Qiang Xue committed
37
	public $controller;
Qiang Xue committed
38 39

	/**
Qiang Xue committed
40 41 42 43 44 45 46 47 48 49
	 * @param string $id the ID of this action
	 * @param Controller $controller the controller that owns this action
	 */
	public function __construct($id, $controller)
	{
		$this->id = $id;
		$this->controller = $controller;
	}

	/**
Qiang Xue committed
50 51 52 53
	 * Runs this action with the specified parameters.
	 * This method is mainly invoked by the controller.
	 * @param array $params action parameters
	 * @return integer the exit status (0 means normal, non-zero means abnormal).
Qiang Xue committed
54
	 */
Qiang Xue committed
55
	public function runWithParams($params)
Qiang Xue committed
56
	{
Qiang Xue committed
57
		try {
Qiang Xue committed
58
			$ps = ReflectionHelper::extractMethodParams($this, 'run', $params);
Qiang Xue committed
59 60
		} catch (Exception $e) {
			$this->controller->invalidActionParams($this, $e);
Qiang Xue committed
61
			return 1;
Qiang Xue committed
62
		}
Qiang Xue committed
63 64 65 66
		if ($params !== $ps) {
			$this->controller->extraActionParams($this, $ps, $params);
		}
		return (int)call_user_func_array(array($this, 'run'), $ps);
Qiang Xue committed
67 68
	}
}