欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

YII框架常用技巧總結(jié)

 更新時間:2019年04月27日 08:56:26   作者:雨落知音  
這篇文章主要介紹了YII框架常用技巧,結(jié)合實例形式總結(jié)分析了Yii框架控制器、查詢、表單驗證、SQL查詢等常用操作技巧與相關注意事項,需要的朋友可以參考下

本文實例總結(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ī)則

復制代碼 代碼如下:
[['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'The combination of Store ID and Member Name has already been taken.'],

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中讀取文件的8種方法和代碼實例

    PHP中讀取文件的8種方法和代碼實例

    這篇文章主要介紹了PHP中讀取文件的8種方法和代碼實例,本文總結(jié)了PHP中讀取文件的8個函數(shù),每一個都附有使用例子及注意事項等,需要的朋友可以參考下
    2014-08-08
  • ThinkPHP V2.2說明文檔沒有說明的那些事實例小結(jié)

    ThinkPHP V2.2說明文檔沒有說明的那些事實例小結(jié)

    這篇文章主要介紹了ThinkPHP V2.2說明文檔沒有說明的那些事,實例分析了ThinkPHP中常用的技巧,需要的朋友可以參考下
    2015-07-07
  • thinkPHP5框架實現(xiàn)基于ajax的分頁功能示例

    thinkPHP5框架實現(xiàn)基于ajax的分頁功能示例

    這篇文章主要介紹了thinkPHP5框架實現(xiàn)基于ajax的分頁功能,結(jié)合實例形式分析了thinkPHP5框架上進行ajax分頁操作的具體步驟、實現(xiàn)代碼與相關操作方法,需要的朋友可以參考下
    2018-06-06
  • 強制PHP命令行腳本單進程運行的方法

    強制PHP命令行腳本單進程運行的方法

    本文介紹了一個強制PHP在單進程中執(zhí)行的函數(shù),多用在php命令行中和一些特殊需求的地方,需要的朋友可以參考下
    2014-04-04
  • 33道php常見面試題及答案

    33道php常見面試題及答案

    這篇文章主要介紹了33道php常見面試題及答案,都是平時面試的時候經(jīng)常會遇到的,小伙伴們仔細了解下吧。
    2015-07-07
  • php支付寶在線支付接口開發(fā)教程

    php支付寶在線支付接口開發(fā)教程

    這篇文章主要為大家詳細介紹了php支付寶在線支付接口開發(fā)教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • thinkphp6如何使用中間件記錄行為日志

    thinkphp6如何使用中間件記錄行為日志

    這篇文章主要介紹了thinkphp6如何使用中間件記錄行為日志問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • php中的PHP_EOL換行符詳細解析

    php中的PHP_EOL換行符詳細解析

    看手冊時發(fā)現(xiàn)PHP_EOL這個變量,查了下資料,原來是相當于換行符。在PHP中可以用PHP_EOL來替代,以提高代碼的源代碼級可移植性
    2013-10-10
  • PHP 自動加載的簡單實現(xiàn)(推薦)

    PHP 自動加載的簡單實現(xiàn)(推薦)

    下面小編就為大家?guī)硪黄狿HP 自動加載的簡單實現(xiàn)(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • laravel接管Dingo-api和默認的錯誤處理方式

    laravel接管Dingo-api和默認的錯誤處理方式

    今天小編就為大家分享一篇laravel接管Dingo-api和默認的錯誤處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-10-10

最新評論