The Method of Using Memcached to Cache Data in ThinkPHP Framework

  • 2021-09-16 06:26:32
  • OfStack

This paper illustrates the method of using Memcached to cache data in ThinkPHP framework. Share it for your reference, as follows:

ThinkPHP uses files to cache data by default, and supports other caching methods such as Memcache. There are two PHP extensions: Memcache and Memcached. Memcahe is officially explained, mainly saying Memcached under 1.

Compared with PHP Memcache, php Memcached is an extension of libmemcached based on native c, which is more perfect. It is recommended to replace it with php memcached.

Version 3.2. 2 started with the built-in Memcached driver (ThinkPHP/Library/Think/Cache/Driver/Memcached. class. php), but the documentation did not explain the usage. It was successfully tested by looking at the source code configuration.

There is an bug has not been repaired so far, that is, the expiration time is 0. In theory, it should be permanent cache, but it is not processed in the driver and will expire immediately. The set method is modified as follows


 public function set($name, $value, $expire = null) {
  N('cache_write',1);
  if(is_null($expire)) {
   $expire = $this->options['expire'];
  }
  $name = $this->options['prefix'].$name;
  if (empty($expire))
   $time = 0;
  else
   $time = time() + $expire;
  if($this->handler->set($name, $value, $time)) {
   if($this->options['length']>0) {
    //  Record cache queue 
    $this->queue($name);
   }
   return true;
  }
  return false;
 }

Add in the configuration file config. php


// Cache configuration 
 'DATA_CACHE_TYPE' => 'Memcached',
 'MEMCACHED_SERVER' => array(
  array('127.0.0.1', 11211, 0)
 ),

In the driver is the call:


Memcached::addServers(array)

You can add multiple cache servers

Another configuration item is MEMCACHED_LIB, which calls:


Memcached::setOptions(array)

For specific options, please refer to PHP Chinese Manual

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

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


Related articles: