国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

YII框架常用技巧總結

2024-05-05 00:08:39
字體:
來源:轉載
供稿:網友

本文實例總結了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 數據:

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=news&id=1Yii::$app->request->url

或者

Yii::$app->request->requestUri

只想獲取url中的參數部分

# r=news&id=1Yii::$app->getRequest()->queryString;

獲取某個參數的值,比如id

Yii::$app->getRequest()->getQuery('id'); //get parameter 'id'

獲?。ǔ蛎獾模┦醉摰刂?/p>

# /public/index.phpYii::$app->user->returnUrl;

獲取Referer

Yii::$app->request->headers['Referer']

或者

Yii::$app->getRequest()->getReferrer()

 

希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 招远市| 邢台县| 泽库县| 宁城县| 揭西县| 图们市| 鹿泉市| 米易县| 拉孜县| 太仆寺旗| 县级市| 巴塘县| 瑞金市| 福安市| 尚志市| 长顺县| 西华县| 宁德市| 吴堡县| 大悟县| 金塔县| 什邡市| 喀喇沁旗| 仲巴县| 墨脱县| 镇康县| 德庆县| 平谷区| 和顺县| 龙江县| 巴林左旗| 本溪| 靖州| 苏州市| 麻江县| 海宁市| 乐业县| 曲松县| 库车县| 正安县| 楚雄市|