PHP Yii框架的动作(Action)有两种方式:
- 写在控制器类中的动作方法:动作函数必须以action为前缀,比如actionLogin();
- 自定义动作类:继承父类CAction;
写在控制器类的动作函数这种方式比较简单,此处仅举一个例子,并不做详述:
class UserController extends CController{
public function actionLogin() {
}
}
自定义动作需要三步:
- 编写自定义动作类,继承CAction类;
- 编写run函数,实现动作逻辑;
- 在控制器中注册自定义动作。
编写自定义动作类,编写run方法。
<?php
/**
* 自定义Action
* @author wangyalsong
*
*/
class SayAction extends CAction{
public function run($classname, $age=20){
echo "SayAction,run:Hello, I`m ".$this->name.'My class is '.$classname." 班. age is {$age}<br>";
}
}
自定义动作类中定义了run方法,并且传入了两个参数。
注意,方法的名字必须是run,千万别写错了,因为,在父类CAction中,已经明确定义了该方法名称:
/**
* Runs the action with the supplied request parameters.
* This method is internally called by {@link CController::runAction()}.
* @param array $params the request parameters (name=>value)
* @return boolean whether the request parameters are valid
* @since 1.1.7
*/
public function runWithParams($params)
{
$method=new ReflectionMethod($this, 'run');
if($method->getNumberOfParameters()>0)
return $this->runWithParamsInternal($this, $method, $params);
else
return $this->run();
}
自定义动作类写好后,下一步,就是要在控制类中注册该动作了。
上一步,我们编写的run方法,需要传入两个参数,所以在控制类中,注册动作的时候,要同时传入参数。
在控制器中注册动作,需要复写父类CController的actions方法。
class UserController extends CController{
public function actionLogin() {
}
public function actions(){
return array(
'say'=>array(
'class'=>'application.controllers.user.SayAction',//动作类目录别名
'name'=>'wangyuchun',//传入参数
),
);
}
}