注:以YII登录体系(上一章)代码为基础 ----- http://blog.csdn.net/h_l_s/article/details/50588254
在下面的代码中:
filters函数为过滤函数,在执行User的动作前,都会先执行访问这个函数
过滤具体方法在 filters 以return array() 返回
具体方法:
1.在UserController下直接写一个方法,做为具体的过滤方法 函数名称规则为 filter+Name 函数默认一个参数$filterChain.同时如果过滤通过要执行
$filterChain->run ();
才会继续执行。如下面代码中的filterA()函数
2.在protected文件下创建filters文件夹,在filter文件夹下创建过滤类方法 继承 CFilter。在例子中TestFilter代码将在下面给出
3.类似与postOnly方法
注:过滤方法可以通过操作符 - 或 + 来控制某个动作执行过滤动作,或不过滤
<?php
class UserController extends Controller{
public function filters(){
return array(
'A',
array(
'application.filters.TestFilter',//application.filters.TestFilter - delete, update 适用于所有控制器,除去delete,update
'unit'=>'second',//给类中的unit属性赋值
),
'postOnly + delete,update',//只能通过post方式,访问delte和update动作
);
}
public function filterA($filterChain){
if(Yii::app()->user->isGuest){//判断是否登录,没有登录跳转到user/login中
$url=$this->createUrl('user/login');
echo "<script>location.href='$url'</script>";
}
else{
Yii::app()->user->setState('m','OK');
}
$filterChain->run ();
}
public function actionIndex(){
echo "Index--".Yii::app()->user->name;
}
public function actionTest(){
echo 'TEST';
}
public function actionLogout(){
Yii::app()->user->logout();
}
public function actionLogin(){
var_dump(Yii::app()->user->isGuest);
$identity=new UserIdentity("username","password");//web/auth/CUserIdentity.php
$result=$identity->authenticate();
if($result){
Yii::app()->user->login($identity);//web/auth/CWebUs
$this->redirect(array('user/index'));//跳转
}
}
public function actionUpdate(){
}
public function actionDelete(){
}
}
?>
<?php
class TestFilter extends<?php
class TestFilter extends CFilter{
public $unit;
protected function preFilter($filterChain){//过滤之前
if($this->unit=='second'){
//echo 'to do something';
return true;
}
else{
return false;
}
}
protected function postFilter($filterChain){
// 过滤动作执行之后应用的逻辑
}
}
?>{
public $unit;
protected function preFilter($filterChain){//过滤之前
if($this->unit=='second'){
//echo 'to do something';
return true;
}
else{
return false;
}
}
protected function postFilter($filterChain){
// 过滤动作执行之后应用的逻辑
}
}
?>