YII框架常用技巧總結(jié)
本文實例總結(jié)了YII框架常用技巧。分享給大家供大家參考,具體如下:
獲取當前Controller name和action name(在控制器里面使用)
echo $this->id; echo $this->action->id;
控制器獲取當前模塊
$this->module->id
不生成label標簽
// ActiveForm類 $form->field($model, '字段名')->passwordInput(['maxlength' => true])->label(false)
Yii2 獲取接口傳過來的 JSON 數(shù)據(jù):
Yii::$app->request->rawBody;
防止 SQL 和 Script 注入:
use yii\helpers\Html; use yii\helpers\HtmlPurifier; echo Html::encode($view_hello_str) //可以原樣顯示<script></script>代碼 echo HtmlPurifier::process($view_hello_str) //可以過濾掉<script></script>代碼
大于、小于條件查詢
// SELECT * FROM `order` WHERE `subtotal` > 200 ORDER BY `id` $orders = $customer->getOrders() ->where(['>', 'subtotal', 200]) ->orderBy('id') ->all();
搜索的時候添加條件篩選
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); // $dataProvider->query->andWhere(['pid' => 0]); $dataProvider->query->andWhere(['>', 'pid', 0]); //可選傳參 $dataProvider->query->andFilterWhere(['id'=>isset($id)?$id:null]);
有兩種方式獲取查詢出來的 name 為數(shù)組的集合 [name1, name2, name3]:
方式一:
return \yii\helpers\ArrayHelper::getColumn(User::find()->all(), 'name');
方式二:
return User::find()->select('name')->asArray()->column();
打印數(shù)據(jù):
// 引用命名空間 use yii\helpers\VarDumper; // 使用 VarDumper::dump($var); // 使用2 第二個參數(shù)是數(shù)組的深度 第三個參數(shù)是是否顯示代碼高亮(默認不顯示) VarDumper::dump($var, 10 ,true);die;
表單驗證,只要需要一個參數(shù):
public function rules() { return [ [['card_id', 'card_code'], function ($attribute, $param) {//至少要一個 if (empty($this->card_code) && empty($this->card_id)) { $this->addError($attribute, 'card_id/card_code至少要填一個'); } }, 'skipOnEmpty' => false], ]; }
SQL is not null條件查詢
// ['not' => ['attribute' => null]] //['ISNULL(`attribute`)'=>true] $query = new Query; $query->select('ID, City,State,StudentName') ->from('student') ->where(['IsActive' => 1]) ->andWhere(['not', ['City' => null]]) ->andWhere(['not', ['State' => null]]) ->orderBy(['rand()' => SORT_DESC]) ->limit(10);
校驗 point_template_id 在 PointTemplate 是否存在
public function rules() { return [ [['point_template_id'], 'exist', 'targetClass' => PointTemplate::className(), 'targetAttribute' => 'id', 'message' => '此{attribute}不存在。' ], ]; }
Yii給必填項加星
div . required label:after { content: " *"; color: red; }
執(zhí)行SQL查詢并緩存結(jié)果
$styleId = Yii::$app->request->get('style'); $collection = Yii::$app->db->cache(function ($db) use ($styleId) { return Collection::findOne(['style_id' => $styleId]); }, self::SECONDS_IN_MINITUE * 10);
場景:
數(shù)據(jù)庫有user表有個avatar_path字段用來保存用戶頭像路徑
需求: 頭像url需要通過域名http://b.com/作為基本url
目標: 提高代碼復用
此處http://b.com/可以做成一個配置
示例:
User.php
class User extends \yii\db\ActiveRecord { ... public function extraFields() { $fields = parent::extraFields(); $fields['avatar_url'] = function () { return empty($this->avatar_path) ? '可以設置一個默認的頭像地址' : 'http://b.com/' . $this->avatar_path; }; return $fields; } ... }
ExampleController.php
class ExampleController extends \yii\web\Controller { public function actionIndex() { $userModel = User::find()->one(); $userData = $userModel->toArray([], ['avatar_url']); echo $userData['avatar_url']; // 輸出內(nèi)容: http://b.com/頭像路徑 } }
Model 里面 rules 聯(lián)合唯一規(guī)則
Model多個字段一條規(guī)則不同提示
[['name', 'email', 'subject', 'body'], 'required','message'=>'{attribute} 必須'],
標量查詢
Post::find()->select('title')->where(['user_id' => $userId])->scalar();
生成 SQL:
SELECT `title` FROM `post` WHERE `user_id` = 1
直接輸出 title 的值。
如果 select('title') 不寫的話,生成 SQL 是:
`SELECT * FROM `post` WHERE `user_id`=1`
直接輸出 id 的值
表單驗證,去除首尾空格:
public function rules() { return [[title', 'content'],'trim']]; }
單獨為某個Action關閉 Csrf 驗證
新建一個Behavior
use Yii; use yii\base\Behavior; use yii\web\Controller; class NoCsrf extends Behavior { public $actions = []; public $controller; public function events() { return [Controller::EVENT_BEFORE_ACTION => 'beforeAction']; } public function beforeAction($event) { $action = $event->action->id; if (in_array($action, $this->actions)) { $this->controller->enableCsrfValidation = false; } } }
然后在Controller中添加Behavior
public function behaviors() { return [ 'csrf' => [ 'class' => NoCsrf::className(), 'controller' => $this, 'actions' => [ 'action - name' ] ] ]; }
LIKE 查詢 單邊加 %
['like', 'name', 'tester'] 會生成 name LIKE ' % tester % '。 ['like', 'name', ' % tester', false] => name LIKE ' % tester' $query = User::find()->where(['LIKE', 'name', $id . ' % ', false]);
SQL 隨機抽取十名幸運用戶
$query = new Query; $query->select('ID, City,State,StudentName') ->from('student') ->where(['IsActive' => 1]) ->andWhere(['not', ['State' => null]]) ->orderBy(['rand()' => SORT_DESC]) ->limit(10);
關于事務:
Yii::$app->db->transaction(function () { $order = new Order($customer); $order->save(); $order->addItems($items); }); // 這相當于下列冗長的代碼: $transaction = Yii::$app->db->beginTransaction(); try { $order = new Order($customer); $order->save(); $order->addItems($items); $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); throw $e; }
批量插入數(shù)據(jù)
第一種方法
$model = new User(); foreach ($data as $attributes) { $_model = clone $model; $_model->setAttributes($attributes); $_model->save(); }
第二種方法
$model = new User(); foreach ($data as $attributes) { $model->isNewRecord = true; $model->setAttributes($attributes); $model->save() && $model->id = 0; }
URL操作
獲取url中的host信息
Yii::$app->request->getHostInfo()
獲取url中的路徑信息(不包含host和參數(shù)):
Yii::$app->request->getPathInfo()
獲取不包含host信息的url(含參數(shù)):
# /public/index.php?r=news&id=1 Yii::$app->request->url
或者
Yii::$app->request->requestUri
只想獲取url中的參數(shù)部分
# r=news&id=1 Yii::$app->getRequest()->queryString;
獲取某個參數(shù)的值,比如id
Yii::$app->getRequest()->getQuery('id'); //get parameter 'id'
獲取(除域名外的)首頁地址
# /public/index.php Yii::$app->user->returnUrl;
獲取Referer
Yii::$app->request->headers['Referer']
或者
Yii::$app->getRequest()->getReferrer()
更多關于Yii相關內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎教程》、《php面向?qū)ο蟪绦蛟O計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
- PHP YII框架開發(fā)小技巧之模型(models)中rules自定義驗證規(guī)則
- yii2 頁面底部加載css和js的技巧
- Yii基于數(shù)組和對象的Model查詢技巧實例詳解
- Yii2使用小技巧之通過 Composer 添加 FontAwesome 字體資源
- Yii使用技巧大匯總
- yii2-GridView在開發(fā)中常用的功能及技巧總結(jié)
- Yii編程開發(fā)常見調(diào)用技巧集錦
- YII框架行為behaviors用法示例
- Yii2框架實現(xiàn)數(shù)據(jù)庫常用操作總結(jié)
- PHP的Yii框架中過濾器相關的使用總結(jié)
- YiiFramework入門知識點總結(jié)(圖文教程)
相關文章
ThinkPHP V2.2說明文檔沒有說明的那些事實例小結(jié)
這篇文章主要介紹了ThinkPHP V2.2說明文檔沒有說明的那些事,實例分析了ThinkPHP中常用的技巧,需要的朋友可以參考下2015-07-07thinkPHP5框架實現(xiàn)基于ajax的分頁功能示例
這篇文章主要介紹了thinkPHP5框架實現(xiàn)基于ajax的分頁功能,結(jié)合實例形式分析了thinkPHP5框架上進行ajax分頁操作的具體步驟、實現(xiàn)代碼與相關操作方法,需要的朋友可以參考下2018-06-06