The principle and use of the TP5 cache

Source: Internet
Author: User
Tags time 0 value store
In today's high-traffic Internet, the importance of cache is self-evident. THINKPHP5, as the main domestic framework, provides a powerful cache function. Let us follow this article to analyze the principle and use of TP5 cache.

Why do I need cache?

Suppose there is a fiction net, and there are a lot of readers, there is a new chapter updated, then there may be tens of thousands of hundreds of thousands of of traffic in a minute.

If there is no cache, the same content will go to the database to repeat the query, the site may be hung up a bit.

The pursuit of performance of the Web site should take full advantage of the cache, common cache types have File,memcache,redis, and so on, not to mention their differences

Today we analyze the internal implementation principle of the TP5 cache.

First look at how the official document uses the cache.

For example, the static method of calling the cache class set can be used directly, we look at the cache class file in the Application/thinkphp/library/think directory

   protected static $instance = [];       public static $readTimes   = 0;       public static $writeTimes  = 0;      /**     * Operation Handle     * @var Object     * @access protected *     /    protected static $handler;     /** *     Write Cache     * @access public     * @param string        $name cache Identity     * @param mixed         $value  store data c19/>* @param int|null      $expire  Effective time 0 is permanent     * @return Boolean     *    /public static function set ($ Name, $value, $expire = null)    {self        :: $writeTimes + +;                Return Self::init ()->set ($name, $value, $expire);    }

See the original Set method is this, where Writetimes is the cache class static variables, the main record cache read the number of times, this is not the focus.

Notice, there is a static variable named $instance, the last time I said that the name of large probability is a singleton mode.

The focus of the Set method is the Init method

Let's look at the Init method again.

  public static function init (array $options = [])    {        if (Is_null (self:: $handler)) {            //automatic initialization of cache            if (!empty ( $options) {                            $connect = Self::connect ($options);            } elseif (' complex ' = = Config::get (' Cache.type ')) {                            $ Connect = Self::connect (Config::get (' Cache.default '));            } else {                            $connect = Self::connect (config::get (' cache '));            }            Self:: $handler = $connect;        }        Return self:: $handler;    }

Handler is the handle of the operation (giant cake:-)), here a look, sure enough is a singleton mode, if the handle is empty to initialize the object, or directly return. Handle

Again, the focus here is the Connect function, and the parameters passed in are configuration information

Again, we look at the Connect method

/** * Connection Cache * @access public * @param array $options configuration array * @ param bool|string $name Cache connection ID true Force Reconnect * @return Driver */public static function connect (array $options        = [], $name = False) {$type =!empty ($options [' type '])? $options [' type ']: ' File ';        if (false = = = $name) {$name = MD5 (serialize ($options));  if (true = = = $name | |!isset (self:: $instance [$name])) {$class = False!== Strpos ($type, ' \ \ ')? $type : ' \\think\\cache\\driver\\ '.            Ucwords ($type);            Record initialization information App:: $debug && Log::record (' [CACHE] INIT '. $type, ' info ');            if (true = = = $name) {return new $class ($options);            } else {self:: $instance [$name] = new $class ($options);    }} return Self:: $instance [$name]; }

Self:: $instance [$name] = new $class ($options); In this sentence, we can know the real identity of the handle pull,
$class = False!== Strpos ($type, ' \ \ ')? $type: ' \\think\\cache\\driver\\ '. Ucwords ($type);
The meaning of this sentence is that the class name is determined by type, and if the type does not contain a backslash, then class = \think\cache\driver\.ucwords ($type)
Thinkphp is the alias of think as the core directory, so his true path is \thinkphp\libray\\think\driver\.ucwords ($type)
Depending on the automatic loading of the urine, it is natural to go to the folder to load the corresponding object
(In addition, this is a feature of PHP dynamic variables, in fact, and the Factory mode of a principle, the operation of dynamic decision-making object)
What is type? Type is the parameter passed in by the function, that is, the configuration information, we look at the configuration information
Type is the drive mode, if we type is file, then use the document driver, instantiate is \think\cache\driver\file.class
Let's look at what's in the \think\cache\driver file, and we'll know how many cache drivers thinkphp give us.

It turns out there are so many!

Go in.

Each file, we can find one thing in common, each class inherits the abstract class Driver

Driver determines what each cache driver should look like, and their approach is essentially the same, and the way it is implemented varies from one drive to another.

In fact, this is the adapter mode, if it is our own writing, of course, will not write so many pull, but TP5 is for the benefit of the vast number of PHP developers, so we have written so many different drivers for us to use.

Let's focus on Redis, and if you're going to experiment, remember to change the Cache.type in config to Redis.

There are few methods for Redis classes, first look at the constructors

Public function __construct ($options = [])    {        if (!extension_loaded (' Redis ')) {            throw new \ Badfunctioncallexception (' not Support:redis ');        }        if (!empty ($options)) {            $this->options = Array_merge ($this->options, $options);        }        $func          = $this->options[' persistent ')? ' Pconnect ': ' Connect ';        $this->handler = new \redis;        $this->handler-> $func ($this->options[' host '], $this->options[' Port '), $this->options[' timeout ');        if ('! = $this->options[' password ') {            $this->handler->auth ($this->options[' password ']);        }        if (0! = $this->options[' select ') {            $this->handler->select ($this->options[' select ']);        }    }

Visible TP5 Redis driver is based on Phpredis, Handler is an instantiated Phpredis class, so choose which driver, the cache class is naturally which drive.
So if you want to use TP5 Redis, you must first install the Phpredis extension.
This is the way to parse the Redis overridden set method

/** * Write Cache * @access public * @param string $name cache variable name * @param m ixed $value Store data * @param integer $expire effective time (seconds) * @return Boolean */Public function set ($name, $        Value, $expire = null) {if (Is_null ($expire)) {$expire = $this->options[' expire '];        } if ($this->tag &&! $this->has ($name)) {$first = true;        } $key = $this->getcachekey ($name);  Cache processing of array/object data to ensure data integrity Byron sampson<xiaobo.sun@qq.com> $value = (is_object ($value) | | Is_array ($value))?        Json_encode ($value): $value;        if (Is_int ($expire) && $expire) {$result = $this->handler->setex ($key, $expire, $value);        } else {$result = $this->handler->set ($key, $value);        } isset ($first) && $this->settagitem ($key);    return $result; }

The original Phpredis set method can only be a normal key-value pair, and the overridden set method is now a key, an array, which is a very useful method

You can see how the implementation works by serializing arrays or objects into JSON, and deserializing them into arrays when values are taken.

Here we have a basic analysis of how a driver is implemented, first of all must inherit the driver class, implement the driver prescribed method, and then give handler to the cache class to use

We go back to the cache class

You can see how the cache class calls the function of the basic bucket is this, init () get to Handler, and then manipulate the handler object, which is our real object, here is Phpredis class,

Of course, we are not able to directly manipulate the Phpredis class, can only use the few methods of the cache class, so some people are not satisfied, because the queue, set and, hash all think no way to use, I also see some students on the internet to rewrite TP5 Redis class

In fact, it is not necessary, the cache class has exposed an interface to us.

We can do this.

        $res  = Cache::init ();                $redis = $res->handler ();                $redis->lpush (' Test ', 111);                $redis->rpush (' Test ', 111);                $redis->lpop (' Test ');

Obtained handler is also obtained Phpredis, so you can use Phpredis native method, and is a singleton mode Oh, no new objects additional consumption

This is the end of this article, if you want to know more about how to use the cache class, you can look at the source code as described above, or consult the official documentation.

Although not explained how to use, but analysis of the cache implementation principle to improve our programming abstraction level, the above analysis of the source code can also be used to analyze the other core class library.

Related reading:

ThinkPHP5 Mall Project actual combat video tutorial courseware source sharing

THINKPHP5 Get started this knowledge

thinkphp5.0 the operation of the Learning Notes database

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.