日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Yii2 behavior运用

發(fā)布時間:2023/12/10 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Yii2 behavior运用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1 class ReturnDataTypeBehaviors extends Behavior 2 { 3 4 public $type = 'json'; 5 public $pcOrMobile = 'pc'; // or mobile 6 7 //控制器執(zhí)行之后事件 8 public function events() 9 { 10 return [Controller::EVENT_BEFORE_ACTION => 'beforeType']; 11 } 12 13 /** 14 * 返回數(shù)據(jù)類型判斷 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 ,設(shè)定請求返回的數(shù)據(jù)

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 * 默認(rèn)分頁值 默認(rèn)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 //設(shè)置回調(diào)url 35 $this->_redirectUrl(); 36 // 登錄驗證 37 $this->_checkLogin(); 38 //session存留時間 39 $this->_setSessionTime(); 40 } 41 42 // 登錄回調(diào) 43 private function _redirectUrl() 44 { 45 $redirectUrl = Yii::$app->request->url; 46 47 if ($redirectUrl == '/site/login') { 48 49 $redirectUrl = '/desktop'; 50 } 51 //設(shè)置登錄后的回調(diào)路徑 52 Yii::$app->session->setFlash('redirectUrl', $redirectUrl); 53 } 54 55 // 權(quán)限驗證 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 //設(shè)置session的存儲時間 79 private function _setSessionTime() 80 { 81 Yii::$app->session->setTimeout(1440 * 2 ); 82 } 83 84 }

?

Controller::EVENT_BEFORE_ACTION => 'beforeType' 觸發(fā)事件調(diào)用‘beforeType’方法

轉(zhuǎn)載于:https://www.cnblogs.com/xp796/p/5704297.html

總結(jié)

以上是生活随笔為你收集整理的Yii2 behavior运用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。