1 class ReturnDataTypeBehaviors extends Behavior 2 { 3 4 public $type = ‘json‘; 5 public $pcOrMobile = ‘pc‘; // or mobile 6 7 //控制器执行之后事件 8 public function events() 9 { 10 return [Controller::EVENT_BEFORE_ACTION => ‘beforeType‘]; 11 } 12 13 /** 14 * 返回数据类型判断 15 * @param $event 16 * @return bool 17 */ 18 public function beforeType($event) 19 { 20 if ($this->pcOrMobile == ‘pc‘) { 21 if (Yii::$app->request->isAjax) { 22 if ($this->type == ‘json‘) { 23 Yii::$app->response->format = Response::FORMAT_JSON; 24 } elseif ($this->type == ‘xml‘) { 25 Yii::$app->response->format = Response::FORMAT_XML; 26 } 27 } 28 } else { 29 if ($this->type == ‘json‘) { 30 Yii::$app->response->format = Response::FORMAT_JSON; 31 } elseif ($this->type == ‘xml‘) { 32 Yii::$app->response->format = Response::FORMAT_XML; 33 } 34 } 35 return true; 36 } 37 38 }
写在BaseController 里面 ,其他的控制器继承Base ,设定请求返回的数据
1 <?php 2 3 namespace app\controllers; 4 5 use app\behaviors\ReturnDataTypeBehaviors; 6 use app\helpers\Util; 7 use yii\helpers\Url; 8 use yii\web\Controller; 9 use app\models\Configuration; 10 use Yii; 11 12 class BaseController extends Controller 13 { 14 /** 15 * 默认分页值 默认10 16 */ 17 const PAGE_SIZE = 6; 18 19 20 public function behaviors() 21 { 22 return [ 23 24 ‘myBehavior‘ => [ 25 26 ‘class‘ => ReturnDataTypeBehaviors::className(), 27 # ‘type‘=>‘json‘, 28 #‘pcOrMobile‘=>‘pc‘ 29 ] 30 ]; 31 } 32 public function init() 33 { 34 //设置回调url 35 $this->_redirectUrl(); 36 // 登录验证 37 $this->_checkLogin(); 38 //session存留时间 39 $this->_setSessionTime(); 40 } 41 42 // 登录回调 43 private function _redirectUrl() 44 { 45 $redirectUrl = Yii::$app->request->url; 46 47 if ($redirectUrl == ‘/site/login‘) { 48 49 $redirectUrl = ‘/desktop‘; 50 } 51 //设置登录后的回调路径 52 Yii::$app->session->setFlash(‘redirectUrl‘, $redirectUrl); 53 } 54 55 // 权限验证 56 private function _rbac() 57 { 58 59 //超级管理员不用过滤 60 61 62 } 63 64 // 登录验证 65 private function _checkLogin() 66 { 67 if (!(Yii::$app->request->url == ‘/site/login‘) && !Yii::$app->user->getId()) { 68 header(‘Location:‘.Yii::$app->request->getHostInfo().‘/site/login‘); 69 exit; 70 } 71 72 } 73 //弹出小框提示 74 public function TipsBox($msg=‘‘,$url=‘‘) 75 { 76 77 } 78 //设置session的存储时间 79 private function _setSessionTime() 80 { 81 Yii::$app->session->setTimeout(1440 * 2 ); 82 } 83 84 }
Controller::EVENT_BEFORE_ACTION => ‘beforeType‘ 触发事件调用‘beforeType’方法
时间: 2024-11-05 08:12:59