Explanation of five built-in behavior classes in yii2 tutorial, and explanation of yii2

Source: Internet
Author: User

Explanation of five built-in behavior classes in yii2 tutorial, and explanation of yii2

Preface

As we all know, learning all the knowledge requires a gradual process and the same behavior. Before we learn how to create a behavior and then easily inject it into the component class, let's take a look at the five built-in behavior classes that the yii2 framework has prepared for us ~ Let's take a look at the detailed introduction:

The purpose of this section is to give your friends an overall sense of behavior during use.

Debut

  • TimestampBehavior
  • SluggableBehavior
  • BlameableBehavior
  • AttributeTypecastBehavior
  • AttributeBehavior

Many articles on the Internet only explain TimestampBehavior. Let's talk about this.

TimestampBehavior

The created_at and updated_at fields in the data table corresponding to the model are automatically updated.

To facilitate learning, I have created a member table with the following structure:

For updates to the created_at and updated_at Fields, I want TimestampBehavior to help me to see how it works?

Step 1

Set the model. In the member model corresponding to the Member table, perform the following settings first.

# app\models\Membernamespace app\models;use Yii;use yii\behaviors\TimestampBehavior;class Member extends \yii\db\ActiveRecord { ... public function behaviors(){  return [   [    'class'=>TimestampBehavior::className(),    'attributes'=>[     ActiveRecord::EVENT_BEFORE_INSERT => ['created_at','updated_at'],     ActiveRecord::EVENT_BEFORE_UPDATE => ['created_at'],    ]   ]  ]; } ...}

From the code point of view, two events are started. Note that this event is invalid if it fails to pass the rules verification after the rules verification.

Step 2

Next we will use it in action. In order to make the example more fun, I use the Console mode.

namespace app\commands;use yii\console\Controller;use app\models\Member;class MemberController extends Controller{ public function actionIndex(){  $model = new Member();  $model->username = 'abei';  if($model->save() == false){   var_dump($model->getErrors());  }  var_dump($model->toArray()); }}

Let's see if created_at and updated_at in $ model of var_dump have data?

I think you like the results. By adding an association to the behavior, you can add the time filling function to the Member class. More than that, TimestampBehavior also provides an interesting touch function, it can be used to assign the current timestamp to a specified attribute and save it to the database.

It is possible that the use of this method is closer to the behavior in your mind.

$member->touch('do_time');

Member itself does not have the touch function. Because it is injected into TimestampBehavior, it has the touch method. Compared with writing a method by itself, the behavior can be injected into many classes, and the reuse rate is very high.

AttributeBehavior

Next we will explain the second behavior class of yii2. If you observe carefully, you should be able to find that the above several behavior classes inherit from this class. What is the usage of this class? It supports Automatic Modification of attributes when an AR event is triggered.

Let's assume that a scenario is still the above member data table. We add a token field for it. The value of this field is initialized when the data is generated, and the value is the md5 value of username, this will happen during all member initialization. Now we use AttributeBehavior to fix it.

Step 1 set the Member Model

Or in its behaviors method, we set the following:

// app\models\Member.phpnamespace app\models;use Yii;use yii\behaviors\AttributeBehavior;use yii\db\ActiveRecord;class Member extends \yii\db\ActiveRecord { public function behaviors(){  return [   [    'class' => AttributeBehavior::className(),    'attributes' => [     ActiveRecord::EVENT_BEFORE_INSERT => 'token',    ],    'value' => function ($event) {     return md5($this->username);    },   ],  ]; }}

We still use the action code in the second step of the above example without making any changes. Let's see how the behavior enhances the function of the injected class.

SluggableBehavior

Next we will talk about the SluggableBehavior behavior class, which is rarely mentioned on the Internet and we will not drop it down.

Using SluggableBehavior makes URL beautification more semantic.

Or the above example, if we want to get a member's information through the url, generally write http://abc.com/index.php like this? R = me...

Right, so that we can get the member information of id = 3.
But this url we and search engine do not like, so now we often use http://abc.com/member/view/3 this format, this format is very simple, through url beautification can be easily implemented.

However, this is not our favorite. We are all talking about url semantics. I think the following url is what we want.

  • Http://abc.com/member/wang-hao
  • Http://abc.com/member/beijing...

The username in my data table corresponds to the records of wang hao and beijing xiao si respectively. Such a url is both beautiful and safe.

Next, let's talk about its implementation steps. First, I need to add a field called slug in the member table.

// The migrate code is as follows: $ this-> addColumn ('member', 'slug', $ this-> string (64)-> notNull ());

Configuration Model

First, we still need to inject SluggableBehavior into the Member model to enhance its functionality.

namespace app\models;use Yii;use yii\behaviors\SluggableBehavior;use yii\db\ActiveRecord;class Member extends \yii\db\ActiveRecord{ ... public function behaviors(){  return [   [    'class' => SluggableBehavior::className(),    'attribute' => 'username',    // 'slugAttribute' => 'slug',   ],  ]; }}

Note that the slugattrigatof the yii2 framework is slug by default, and the field we just added to the data table is also called slug, so we do not need to set slugAttribute.

Next, we generate a username = wang hao record. You will find that the slug of this record is automatically filled with wang-hao.

Url beautification

Of course at this moment, through http://abc.com/memberr/wang-hao we still don't get, need UrlMananger support.

Implementation of Action

Next, in our MemberController controller

namespace app\controllers;use yii\web\Controller;use app\models\Member;class MemberController extends Controller{ public function actionSlug($slug) {  $model = Member::find()->where(['slug'=>$slug])->one();  \yii\helpers\VarDumper::dump($model->toArray(),10,true);die(); }}

Next, you access/member/wang-hao and get the desired result.

This situation is often used in many blogs and cms sites. For example, you can visit the moonlight blog to check its url and use SluggableBehavior to help us save the trouble of entering slug and add it automatically.

Of course, this behavior class does not support Chinese characters. If your field is Chinese, it cannot be analyzed. It doesn't matter. Next we will explain how to make it support Chinese characters.

Several parameters about SluggableBehavior are required.

public function behaviors(){ return [  [   'class' => SluggableBehavior::className(),   'attribute' => 'username',   'immutable' => true,   'ensureUnique'=>true,  ], ];}

Immutable: this parameter is set to false by default. When it is set to true, the slug value will not change even if the 'attribute' => 'username' field is updated after a record is generated.

EnsureUnique this parameter defaults to false, when set to true, can effectively avoid slug repetition, if both usernames are called wang hao, the generated slug will be wang-hao and wang-hao-2

The other two

There are still BlameableBehavior and AttributeTypecastBehavior. In fact, you should be able to feel that yii2's built-in behavior is mainly to enhance the attributes of the AR model. After all, this is our most commonly used behavior.

Through the above three behaviors, I think you can easily deal with these two. I will not explain the code and talk about the role of these two actions.

BlameableBehavior

This row automatically fills in the current logon member ID for an ar data table.

public function behaviors() { return [  [   'class' => BlameableBehavior::className(),   'createdByAttribute' => 'author_id',   'updatedByAttribute' => 'updater_id',  ], ];}

If it is a background module, you can set the value field to obtain the logon ID.

AttributeTypecastBehavior

AttributeTypecastBehavior is added when yii2 is in v2.0.10. It mainly provides an action to automatically convert the model attribute format, this is very useful for non-schema databases like MongoDB or Redis.

Currently, this action provides the following types:

const TYPE_INTEGER = 'integer';const TYPE_FLOAT = 'float';const TYPE_BOOLEAN = 'boolean';const TYPE_STRING = 'string';

Of course, it also provides a manual method of typecastAttributes, you can directly call to convert the attribute format.

Last

The above are five built-in behavior classes provided by yii2. These behaviors (mainly the first three) can help us reduce the writing of a lot of code.

Of course, in the subsequent chapters, you will gradually experience more powerful behaviors and look forward to them together.

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.