<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class SessionCheckFilter extends CFilter {
public function init() {
parent::init();
$this->attachBehaviors(array(
'class' => 'ext.behavior.JsonBehavior'
));
}
protected function preFilter($filterChain) {
if (isset(Yii::app()->user->userId) && (!empty(Yii::app()->user->userId))) {
return true;
} else {
_echo(ERROR_SESSION, '用户id获取失败,您需要重新登录');
Yii::app()->user->loginRequired();
return false;
}
}
}
为了简便,你可能会这样写:
<?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class Controller extends CController {
public $layout = '//layouts/column1';
public $menu = array();
public $breadcrumbs = array();
public $error;
public $jsonText;
public function behaviors() {
return array(
'class' => 'ext.behavior.JsonBehavior'
);
}
public function filters() {
return array(
array('application.filters.SessionCheckFilter - user/default/login,user/default/logout,user/default/registration,temp/default/index'),
);
}
protected function beforeAction(CAction $action) {
$this->error = new ErrorCapture();
return true;
}
public function initParams($className = '', $type = 'model') {
$model = null;
if ($type == 'model') {
$model = $className::model();
} else {
$model = new $className();
}
if (isset($_POST[get_class($model) ])) {
$model->attributes = $_POST[get_class($model)];
}
return $model;
}
/**
* 手机客户端的分页,防止分页重复,与网页显示无关
* @param CActiveDataProvider $dataProvider
*
*/
public function page(CActiveDataProvider & $dataProvider) {
$pageCount = $dataProvider->getPagination()->getPageCount();
if ($dataProvider->getTotalItemCount() == 0) {
$this->send(ERROR_EMPTY, 'data empty');
}
else if (isset($_GET['page'])) {
if ($pageCount >= $_GET['page']) {
$this->send(0, $dataProvider->getData());
}
}
else{
$this->send(ERROR_NONE, $dataProvider->getData());
}
}
}
这样就不会在子controller里面写了。但是实际上这不行。这样在父类中写过滤器并不能完成过滤、估计是YII的bug