本文實例總結了YII框架常用技巧。分享給大家供大家參考,具體如下:
獲取當前Controller name和action name(在控制器里面使用)
echo $this->id;
echo $this->action->id;
控制器獲取當前模塊
不生成label標簽
// ActiveForm類
$form->field($model, '字段名')->passwordInput(['maxlength' => true])->label(false)
Yii2 獲取接口傳過來的 JSON 數據:
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 為數組的集合 [name1, name2, name3]:
方式一:
return \yii\helpers\ArrayHelper::getColumn(User::find()->all(), 'name');
方式二:
return User::find()->select('name')->asArray()->column();
打印數據:
// 引用命名空間
use yii\helpers\VarDumper;
// 使用
VarDumper::dump($var);
// 使用2 第二個參數是數組的深度 第三個參數是是否顯示代碼高亮(默認不顯示)
VarDumper::dump($var, 10 ,true);die;
表單驗證,只要需要一個參數:
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;
}
執行SQL查詢并緩存結果
$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);
場景:
數據庫有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']; // 輸出內容: http://b.com/頭像路徑
}
}
Model 里面 rules 聯合唯一規則
復制代碼 代碼如下:
[['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'The combination of Store ID and Member Name has already been taken.'],
Model多個字段一條規則不同提示
[['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;
}
批量插入數據
第一種方法
$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和參數):
Yii::$app->request->getPathInfo()
獲取不包含host信息的url(含參數):
# /public/index.php?r=newsid=1
Yii::$app->request->url
或者
Yii::$app->request->requestUri
只想獲取url中的參數部分
# r=newsid=1
Yii::$app->getRequest()->queryString;
獲取某個參數的值,比如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相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
您可能感興趣的文章:- PHP YII框架開發小技巧之模型(models)中rules自定義驗證規則
- yii2 頁面底部加載css和js的技巧
- Yii基于數組和對象的Model查詢技巧實例詳解
- Yii2使用小技巧之通過 Composer 添加 FontAwesome 字體資源
- Yii使用技巧大匯總
- yii2-GridView在開發中常用的功能及技巧總結
- Yii編程開發常見調用技巧集錦
- YII框架行為behaviors用法示例
- Yii2框架實現數據庫常用操作總結
- PHP的Yii框架中過濾器相關的使用總結
- YiiFramework入門知識點總結(圖文教程)