Summary of Common Skills of YII Framework

  • 2021-12-05 05:57:54
  • OfStack

This paper summarizes the common skills of YII framework with examples. 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;

The controller acquires the current module


$this->module->id

Do not generate label tags


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

Yii2 gets the JSON data 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) // It can be displayed as it is <script></script> Code 
echo HtmlPurifier::process($view_hello_str) // It can be filtered out <script></script> Code 

Greater than and less than conditional queries


// 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->search(Yii::$app->request->queryParams);
// $dataProvider->query->andWhere(['pid' => 0]);
$dataProvider->query->andWhere(['>', 'pid', 0]);
// Optional transmission parameter 
$dataProvider->query->andFilterWhere(['id'=>isset($id)?$id:null]);

There are two ways to get the queried collection of arrays of name [name1, name2, name3]:

Mode 1:


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

Mode 2:


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

Print data:


//  Reference namespace 
use yii\helpers\VarDumper;
//  Use 
VarDumper::dump($var);
//  Use 2  No. 1 2 Parameters are the depth of the array   No. 1 3 The parameter is whether to display code highlighting (not displayed by default) 
VarDumper::dump($var, 10 ,true);die;

Form validation requires only one parameter:


$this->module->id

0

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 whether point_template_id exists in PointTemplate


public function rules()
{
  return [
    [['point_template_id'], 'exist',
      'targetClass' => PointTemplate::className(),
      'targetAttribute' => 'id',
      'message' => ' This {attribute} It doesn't exist. '
    ],
  ];
}

Yii Star Required Items


$this->module->id

3

Execute SQL query and cache results


$this->module->id

4

Scenario:

The database has an user table and an avatar_path field to hold the user avatar path

Requirements: Avatar url needs to pass the domain name http://b. com/as the basic url

Goal: Improve code reuse

Here http://b. com/can be made into one configuration

Example:

User.php


$this->module->id

5

ExampleController.php


$this->module->id

6

rules Union Uniqueness Rule in Model

[['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 1 Rule Different Prompt


[['name', 'email', 'subject', 'body'], 'required','message'=>'{attribute}  Must '],

Scalar query


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

Generate SQL:


$this->module->id

9

Output the value of title directly.

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


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

Output the value of id directly

Form validation, removing the first and last spaces:


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

Turn off Csrf authentication 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 to Controller


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

LIKE query unilateral plus%


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

SQL randomly selected 10 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);

On matters:


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

Insert data in batches

Method 1


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

Method 2


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

URL operation

Getting host information from url


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

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


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

To get an url that does not contain host information (with parameters):


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

Or


Yii::$app->request->requestUri

Just want to get the parameter part of 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 the home page address (except domain name)


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

Get Referer


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

Or


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

For more readers interested in Yii related contents, please check the topics on this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Yii framework.


Related articles: