SoFunction
Updated on 2025-04-04

Summary of common techniques for YII framework

This article summarizes common techniques for YII framework. Share it for your reference, as follows:

Get the current Controller name and action name (used in the controller)

echo $this->id;
echo $this->action->id;

Controller gets the current module

$this->module->id

No label tags are generated

// ActiveForm class$form->field($model, 'Field Name')->passwordInput(['maxlength' => true])->label(false)

Yii2 Get the JSON data transmitted from the interface:

Yii::$app->request->rawBody;

Prevent SQL and Script injection:

use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
echo Html::encode($view_hello_str) //The <script></script> code can be displayed as it isecho HtmlPurifier::process($view_hello_str) //The <script></script> code can be filtered out

Greater than or less than conditional query

// SELECT * FROM `order` WHERE `subtotal` > 200 ORDER BY `id`
$orders = $customer->getOrders()
->where(['>', 'subtotal', 200])
->orderBy('id')
->all();

Add conditional filtering when searching

$dataProvider = $searchModel-&gt;search(Yii::$app-&gt;request-&gt;queryParams);
// $dataProvider-&gt;query-&gt;andWhere(['pid' =&gt; 0]);
$dataProvider-&gt;query-&gt;andWhere(['&gt;', 'pid', 0]);
//Optional pass parameters$dataProvider-&gt;query-&gt;andFilterWhere(['id'=&gt;isset($id)?$id:null]);

There are two ways to get the queryed name as an array set [name1, name2, name3]:

Method 1:

return \yii\helpers\ArrayHelper::getColumn(User::find()->all(), 'name');

Method 2:

return User::find()->select('name')->asArray()->column();

Print data:

// Reference namespaceuse yii\helpers\VarDumper;
// useVarDumper::dump($var);
// Use 2 The second parameter is the depth of the array. The third parameter is whether to display the code highlighting (not displayed by default)VarDumper::dump($var, 10 ,true);die;

Form verification, as long as one parameter is required:

public function rules()
{
  return [
    [['card_id', 'card_code'], function ($attribute, $param) {//At least one      if (empty($this-&gt;card_code) &amp;&amp; empty($this-&gt;card_id)) {
        $this-&gt;addError($attribute, 'Card_id/card_code must be filled in at least one');
      }
    }, 'skipOnEmpty' =&gt; false],
  ];
}

SQL is not null conditional query

// ['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);

Verify that point_template_id exists in PointTemplate

public function rules()
{
  return [
    [['point_template_id'], 'exist',
      'targetClass' =&gt; PointTemplate::className(),
      'targetAttribute' =&gt; 'id',
      'message' =&gt; 'this{attribute}Does not exist。'
    ],
  ];
}

Yii adds stars to the required items

div . required label:after {
  content:
  " *";
  color:
  red;
}

Execute SQL query and cache results

$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);

Scene:

The database has a user table and an avatar_path field is used to save the user avatar path.

Requirements: The avatar url needs to pass the domain name/As a basic url

Goal: Improve code reuse

Here/Can be made into a configuration

Example:

class User extends \yii\db\ActiveRecord
{
...
  public function extraFields()
  {
    $fields = parent::extraFields();
    $fields['avatar_url'] = function () {
      return empty($this-&gt;avatar_path) ? 'You can set a default avatar address' : '/' . $this-&gt;avatar_path;
    };
    return $fields;
  }
...
}

class ExampleController extends \yii\web\Controller
{
  public function actionIndex()
  {
    $userModel = User::find()-&gt;one();
    $userData = $userModel-&gt;toArray([], ['avatar_url']);
    echo $userData['avatar_url']; // Output content: /Avatar path  }
}

The only rules in the Model

Copy the codeThe code is as follows:
[['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'The combination of Store ID and Member Name has already been taken.'],

Model multiple fields with different rules

[['name', 'email', 'subject', 'body'], 'required','message'=&gt;'{attribute} must'],

Scalar query

Post::find()->select('title')->where(['user_id' => $userId])->scalar();

Generate SQL:

SELECT `title` FROM `post` WHERE `user_id` = 1

Directly output the value of title.

If select('title') is not written, the generated SQL is:

`SELECT * FROM `post` WHERE `user_id`=1`

Directly output the value of id

Form verification, remove the beginning and end spaces:

public function rules()
{
  return [[title', 'content'],'trim']];
}

Turn off Csrf verification for an Action alone

Create a new 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;
    }
  }
}

Then add Behavior in Controller

public function behaviors()
{
  return [
    'csrf' => [
      'class' => NoCsrf::className(),
      'controller' => $this,
      'actions' => [
        'action - name'
      ]
    ]
  ];
}

LIKE query One-sided add %

['like', 'name', 'tester'] Will generate name LIKE ' % tester % '。
['like', 'name', ' % tester', false] =&gt; name LIKE ' % tester'
$query = User::find()-&gt;where(['LIKE', 'name', $id . ' % ', false]);

SQL randomly selects ten lucky users

$query = new Query;
$query->select('ID, City,State,StudentName')
  ->from('student')
  ->where(['IsActive' => 1])
  ->andWhere(['not', ['State' => null]])
  ->orderBy(['rand()' => SORT_DESC])
  ->limit(10);

About the transaction:

Yii::$app-&gt;db-&gt;transaction(function () {
  $order = new Order($customer);
  $order-&gt;save();
  $order-&gt;addItems($items);
});
// This is equivalent to the following verbose code:$transaction = Yii::$app-&gt;db-&gt;beginTransaction();
try {
  $order = new Order($customer);
  $order-&gt;save();
  $order-&gt;addItems($items);
  $transaction-&gt;commit();
} catch (\Exception $e) {
  $transaction-&gt;rollBack();
  throw $e;
}

Insert data in batches

The first method

$model = new User();
foreach ($data as $attributes) {
  $_model = clone $model;
  $_model->setAttributes($attributes);
  $_model->save();
}

The second method

$model = new User();
foreach ($data as $attributes) {
  $model->isNewRecord = true;
  $model->setAttributes($attributes);
  $model->save() && $model->id = 0;
}

URL operation

Get host information in url

Yii::$app->request->getHostInfo()

Get path information in the url (not including host and parameters):

Yii::$app->request->getPathInfo()

Get the URL (including parameters) that does not contain host information:

# /public/?r=news&id=1
Yii::$app->request->url

or

Yii::$app->request->requestUri

Just want to get the parameter part in the url

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

Get the value of a parameter, such as id

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

Get (except the domain name) homepage address

# /public/
Yii::$app->user->returnUrl;

Get Referer

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

or

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

For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.