We know that yii2 has a number of built-in behaviors, such as automatic timestamp updates and auto-assigned login member ids. For details, please refer to my previous yii2 Behavior Research topic, which added this CacheableWidgetBehavior to version 2.0.14.

The idea is very simple, you can cache a small widget, the behavior is very low configuration requirements, usually you only need to support the cache component.

Next, I will write a small tutorial in the simplest language, hoping to inspire you.

On a sunny morning, my boss gave me the following requirements:

Small north ah, you give our website to make the latest post 10 blocks. 🐸 🐸 🐸 🐸 ok.

Since it is a block, I naturally thought of small widgets, said to do we do, so I wrote the following code

Structure small pendant

I created a new little widget called newpost.php

// @app/components/NewPost.php namespace app\components; use yii\base\Widget; use app\models\Post; class NewPost extends Widget { public function init(){ parent::init(); } public function run(){ parent::run(); $data = Post::find()->orderBy(["created_at"=>SORT_DESC])->limit(10)->all(); return $this->render('new_post',[ 'data'=>$data ]); }}Copy the code

Then create a view new_post.php under @app/components/views

// new_post.php <ul> <? php foreach($data as $post):? > <li> <? = $post->title; ? > </li> <? php endforeach; ? > </ul>Copy the code

Into the behavior

Given the quiet popularity of the corporate community, I decided to cache this widget using the CacheableWidgetBehavior in yii2 in 2.0.14.

// @app/components/NewPost.php ... use yii\behaviors\CacheableWidgetBehavior; class NewPost extends Widget { ... public function behaviors(){ return [ [ 'class' => CacheableWidgetBehavior::className(), 'cacheDuration' => 60, ] ]; }... }Copy the code

This will cache the entire widget. I use the cacheDuration parameter to set the duration to 60 seconds, and default to 60 seconds if you don’t write.

Since this is cache, let’s look at the Runtime /cache folder

The boss’s reply

When I am in a high mood to show the boss of the time, the boss a sanctimonious said: “small north ah, so bad, I still want to have a new post here can see immediately, otherwise the user experience is bad, in thinking about a way? Reduces database stress and ensures the first time!!”

Oh, good thing I have another trick up my sleeve.

Look at the code

//@app/components/NewPost.php
public function behaviors(){
    return [
        [
            'class' => CacheableWidgetBehavior::className(),
            'cacheDuration' => 0,
            'cacheDependency' => [
                'class' => 'yii\caching\DbDependency',
                'sql' => 'SELECT MAX(updated_at) FROM post',
            ]
        ]
    ];
}Copy the code

I set cacheDuration=0 to never expire, and then added the cacheDependency item to add a database dependency to the behavior to store the last update date of a post, so that when new posts come in, the updated_AT changes invalidate the cache, and then re-query for new posts.

Test success, great joy.

Run to the boss and get off on time benefits.

additional

Since CacheableWidgetBehavior is used, there are also cacheKeyVariations, which are generally configured as follows

public function behaviors(){
    return [
        [
            'class' => CacheableWidgetBehavior::className(),
            'cacheDuration' => 0,
            'cacheKeyVariations' => 1
        ]
    ];
}Copy the code

CacheKeyVariations can be a string or an array, and changes in the values of cacheKeyVariations can also cause the cache to be re-established. Specific how to use to see your needs.

These are just a few uses of CacheableWidgetBehavior. Hopefully, this new built-in behavior in 2.0.14 will help you with your development.