Beige Dahua yii2 cache mechanism file cache


Some brothers will say, what’s the point of file cache? Isn’t it a set and then a get? All you know is fur~

It’s true that cache is a set (put data) and then a get (get data) from the performance layer, but please remember that this is not enough. If you don’t understand the implementation principle and storage characteristics of each cache, you can’t use the scenario, when to use file cache, when to use DB cache, and when to use Memcache. These are That’s what we need to learn.

Still write directory first

  1. Definition of filecache

  2. Basic usage of filecache

  3. Logical implementation of filecache in storing content

Definition of filecache

It may be clear in a word that some data will be saved in the file, and read directly from the file when reading next time, which will divert the pressure.

Basic Usage

To unify the interface, yii2 unifies all types of caching into the following methods.

Get() // get the cache value according to a specified key. If the cache does not exist or has expired, return false
Set() // directly save a value to the cache (regardless of whether it exists, replace it directly)
Add() // save if the cache does not exist at this time, otherwise ignore
Multiget() // get the cache value of multiple keys at one time. The parameter is an array of keys ["key1", "key2"], and the return value is also an array ["key1" = > value1 "," key2 "= > Value2"]
Multiset() // store multiple caches at a time
Mulitadd() // add multiple caches at a time
Delete() // delete a cache
Flush() // delete all caches

I think you can see the above eight methods through the documents. It’s really not difficult. There are two methods that are more important here. They are a little bit poorly understood.


As the name implies, check whether a cache exists (cache expiration = expiration). Note the following points for this function

  1. When the amount of cached data is large, it is faster to use exists than get. However, if there is no native exists in the cache, then exists will simulate it. In this case, exists will not improve the performance of get and filecache.

  2. Exists does not check the cache dependency, so if a cache has dependency and the dependency changes, the value we get through get is false, but it is possible that exists gets true, which should be noted.

getOrSet($key, Closure $closure, $duration = null, $dependency = null)
This is a new method added in v2.0.11.

$data = $cache->getOrSet($key, function () {
    return $this->calculateSomething();

Equate to

$data = $cache->get($key);
if ($data === false) {
    $data = $this->calculateSomething();
    $cache->set($key, $data);

The purpose of this function is simple – if there is one, get it, if not, build it, but the $closure in it, to mention, receives a closure. Closure is a new concept introduced by php5.3. If you don’t know it, you can use the following website to make up lessons…

So we can write a cache code that you may not see very often

$cache->getOrSet(['user','id'=>$id],function($cache) use ($id){
    return User::findOne($id);

Cache each member’s information, use use, minimum code.

The above is yii2 cache’s unified 10 methods for all supported caches. Next, we will make some theoretical explanations for filecache. For your convenience, we use question and answer mode.

The point

God asked:Beige, what do I mean when I look at the documents? Besides a string, the key of get, set and getorset can also receive a data structure?

North brother answer:Yes, you are right. For example, if we want to cache every article now, we can use the following two methods

//Key is string
//Key is a structure, such as an array

These two forms can be used. I think you will ask how these keys are identified. How can I find them in the runtime cache?

God asked:Yes, beige, you are right. For example, my key = ABC. How do I create folders or cache files based on the key when I store them? How do they name them?

North brother answer:Yii’s handling of file cache key is as follows. I’ll answer you with pseudo code.

//Reprocessing the key defined by user cache
If ($key = = string){
    If ($key string only contains numbers or letters & & $key length < = 32){
        return $key;
    Return MD5 (json_encode ($key)); // both the number key and the array key are MD5.

So you can see the cache file that may make you circle, as shown in the following figure

Beige Dahua yii2 cache mechanism file cache

It’s not covered now. But be sure to look at the following code


Statement 1 will generate a 123. Bin cache file, because “123” is a string, while statement 2’s 123 is a number, which will generate the. Bin file after MD5 (123).

Now that you understand the file naming rules, I think God, you must have been confused by the 13, 59, A3, Le folders. Take a closer look, yes, you found…

Is the first two letters of the file name

Congratulations, what an accurate and great discovery it is. However, I think you must have seen such a cache directory

Beige Dahua yii2 cache mechanism file cache

Directory has more than one level, many levels, which makes sense. It can guarantee that there will not be too many files in a folder. But how does this work?

It’s just a variable decision. It’s called directorylevel (1 by default)

$cache->directoryLevel = 3;

Of course, you can also configure it in the cache of the web, or according to the password you just found. If directorylevel = 3, start the file name from the beginning, and make a folder every 2 characters (if the file name is only 3 characters, it’s better to stop when the second one is created).

Good God, now you understand~

God asked:You said I understand. I have another problem. For example, I set a key = ABC cache in my module, and others also set a key = ABC cache (not the same meaning as my key). Isn’t it covered? Can it be avoided?

North brother answer:Yes, you can use a variable called keyprefix, which prefixes the name of your cache file and looks at the code

$cache->keyPrefix = "nai8_";
$cache->set("hello","hello keyPrefix");

give the result as follows

Beige Dahua yii2 cache mechanism file cache

This time you are not afraid to see who dares to conflict with you.

God asked:I’ve basically understood. I’ll ask you another question, and I’ll go back to Huaguoshan after I’ve answered it. For example, I wrote $cache – > set (“a”, “ABC”, 1000). But when I get it, how can Yii know if it’s 1000 seconds, expired or not? I don’t see the number 1000 in the file. Where is it?

North brother answer:You are right. This is to introduce a PHP function — touch(), which can modify the last modification time of a file. When we execute $cache – > set (“a”, “ABC”, 1000), Yii’s filecache does one thing. Look at the code

Touch ("cache file", (time() + 1000));

You see, when we read it, we only need to judge whether the last modification time of FILETIME (“cache file”) is greater than the current time (), which is a simple thing.

OMG~ Fly fly fly ……

But I haven’t finished~

Now let’s start with a short talk about cache dependency (set, add, getorset all have this parameter). What does that mean? Simply speaking, a cache is related to a certain East. When the East changes, the cache fails (since the current expiration time has not yet arrived)

Because of the space problem, we’ll talk about a cache database dependency here. Later, we’ll give a separate article on “Beige big talk yii2 cache mechanism” to talk about various dependencies.

$dependency = new \yii\caching\DbDependency(
    ['sql' => 'SELECT count(*) FROM user']
//When the database field changes, the cache fails
$cache->add('three', 'hello world!', 3000, $dependency);

Dependency is still quite useful, for example, some statistics are displayed for caching, and the cached data can be updated in time when the data changes.

It’s a long speech ~ as the first part of “Beige big talk yii2 caching mechanism”, I hope you like it. For a while, I will focus on sharing yii2 caching mechanism.

Thank you for your support.