Configure cache




How to set the cache

The global cache configuration directly modifies the configuration The cache.php file under the directory.

ThinkPHP uses the think\Cache class (actually just use the think\facade\Cache class) to provide caching function support. Built-in supported cache types include file, memcache, wincache, sqlite, and redis. ThinkPHP's caching class follows the PSR-6 and PSR-16 specifications. Due to the special nature of model and dataset objects (including PDOStatement objects), caching does not support caching model and dataset objects.

The new version of cache supports multi-channel. You can define all cache types and configuration parameters in advance, and then switch at any time when using them. The file cache type is used by default. You can add redis cache support, for example:

return [
    'default'    =>    'file',
    'stores'    =>    [
        // 文件缓存
        'file'   =>  [
            // 驱动方式
            'type'   => 'file',
            // 设置不同的缓存保存目录
            'path'   => '../runtime/file/',
        ],  
        // redis缓存
        'redis'   =>  [
            // 驱动方式
            'type'   => 'redis',
            // 服务器地址
            'host'       => '127.0.0.1',
        ],  
    ],
];

If your application only needs to use one cache type, you can configure it directly and the system will automatically initialize it.

return [
    // 缓存类型为File
    'type'  =>  'file', 
    // 全局缓存有效期(0为永久有效)
    'expire'=>  0, 
    // 缓存前缀
    'prefix'=>  'think',
     // 缓存目录
    'path'  =>  '../runtime/cache/',
];

Cache parameters will differ according to different caching methods. The general cache parameters are as follows:

ParametersDescription
typeCache type
expireCache validity period (default is 0 Represents permanent cache)
prefixCache prefix (default is empty)
serializeCache Serialization and deserialization methods

Use

Set the cache

Set the cache validity period

// 缓存在3600秒之后过期
Cache::set('name', $value, 3600);

You can use the DateTime object to set the expiration time

Cache::set('name', $value, new DateTime('2019-10-01 12:00:00'));

If the setting is successful, return true, otherwise return false.

Cache auto-increment

For cached data of numerical type, you can use the auto-increment operation, for example:

Cache::set('name', 1);
// name自增(步进值为1)
Cache::inc('name');
// name自增(步进值为3)
Cache::inc('name',3);

Only numbers Or perform increment and decrement operations on floating-point data.

Cache decrement

For cached data of numerical type, you can use the decrement operation, for example:

// name自减(步进值为1)
Cache::dec('name');
// name自减(步进值为3)
Cache::dec('name',3);

Get Cache

To obtain cached data, you can use:

Cache::get('name');

If the name value does not exist, false will be returned by default.

Supports specifying default values, for example:

Cache::get('name','');

means that if the name value does not exist, an empty string will be returned.

Append a cached data

If the cached data is an array, you can append a data through the push method.

Cache::set('name', [1,2,3]);
Cache::push('name', 4);
Cache::get('name'); // [1,2,3,4]

Delete cache

Cache::delete('name');

Get and delete cache

Cache::pull('name');

If the name value does not exist, return null.

Clear the cache

Cache::clear();

If it does not exist, write the cache data and return

Cache::remember('start_time', time());

If start_time cache data If it does not exist, the cached data will be set to the current time.

The second parameter can use the closure method to obtain cached data and supports dependency injection.

Cache::remember('start_time', function(Request $request){
    return $request->time();
});

The third parameter of the remember method can set the cache validity period.

Cache tag

Supports tagging cache data, for example:

Cache::tag('tag')->set('name1','value1');
Cache::tag('tag')->set('name2','value2');

// 清除tag标签的缓存数据
Cache::tag('tag')->clear();

And supports specifying multiple cache tag operations at the same time

Cache::tag(['tag1', 'tag2'])->set('name1', 'value1');
Cache::tag(['tag1', 'tag2'])->set('name2', 'value2');

// 清除多个标签的缓存数据
Cache::tag(['tag1','tag2'])->clear();

You can append a cache to the tag

Cache::tag('tag')->append('name3');

Get the cache object

You can get the cache object and call the advanced method of the driver class, for example:

// 获取缓存对象句柄
$handler = Cache::handler();

Assistant function

The system provides the assistant function cache for caching operations. The usage is as follows:

$options = [
     // 缓存类型为File
    'type'   => 'File', 
     // 缓存有效期为永久有效
    'expire' => 0,
     // 指定缓存目录
    'path'   => APP_PATH . 'runtime/cache/', 
];

// 缓存初始化
// 不进行缓存初始化的话,默认使用配置文件中的缓存配置
$cache = cache($options);

// 设置缓存数据
cache('name', $value, 3600);
// 获取缓存数据
var_dump(cache('name'));
// 删除缓存数据
cache('name', NULL);

Cross-application cache

By default, file cache data is differentiated between different applications. If you want to cache cross-applications, you can set a unified data cache path directory.

Switch cache type

If the cache type is not specified, the default cache configuration is read by default and can be switched dynamically

// 使用文件缓存
Cache::set('name','value',3600);
Cache::get('name');

// 使用Redis缓存
Cache::store('redis')->set('name','value',3600);
Cache::store('redis')->get('name');

// 切换到文件缓存
Cache::store('default')->set('name','value',3600);
Cache::store('default')->get('name');

If you want to return the handle of the current cache type object, You can use

// 获取Redis对象 进行额外方法调用
Cache::store('redis')->handler();

to use multiple cache types at the same time

If you want to use multiple cache types at the same time, you can configure the following:

return [
    // 使用复合缓存类型
    'type'  =>  'complex',
    // 默认使用的缓存
    'default'   =>  [
        // 驱动方式
        'type'   => 'file',
        // 缓存保存目录
        'path'   => '../runtime/default',
    ],
    // 文件缓存
    'file'   =>  [
        // 驱动方式
        'type'   => 'file',
        // 设置不同的缓存保存目录
        'path'   => '../runtime/file/',
    ],  
    // redis缓存
    'redis'   =>  [
        // 驱动方式
        'type'   => 'redis',
        // 服务器地址
        'host'       => '127.0.0.1',
    ],     
],
## After #type is configured as complex, you can cache multiple cache types and cache configurations. The method of configuring each cache is the same as before, and you can configure different cache configuration parameters for the same type of cache type (using different cache identifiers). .

return [
    // 缓存配置为复合类型
    'type'  =>  'complex', 
    'default'	=>	[
      'type'	=>	'file',
      // 全局缓存有效期(0为永久有效)
      'expire'=>  0, 
      // 缓存前缀
      'prefix'=>  'think',
       // 缓存目录
      'path'  =>  '../runtime/cache/',
    ],
    'redis'	=>	[
      'type'	=>	'redis',
      'host'	=>	'127.0.0.1',
      // 全局缓存有效期(0为永久有效)
      'expire'=>  0, 
      // 缓存前缀
      'prefix'=>  'think',
    ],    
    // 添加更多的缓存类型设置
];

If the cache type is not specified, the default cache configuration is read by default.

// 使用文件缓存
Cache::set('name','value',3600);
Cache::get('name');

// 使用Redis缓存
Cache::store('redis')->set('name','value',3600);
Cache::store('redis')->get('name');

// 切换到文件缓存
Cache::store('default')->set('name','value',3600);
Cache::store('default')->get('name');

Another way is to call the connect method to dynamically switch caches.

$options = [
    // 缓存类型为File
    'type'  =>  'File', 
    // 缓存有效期为永久有效
    'expire'=>  0, 
    //缓存前缀
    'prefix'=>  'think',
     // 指定缓存目录
    'path'  =>  '../runtime/cache/',
];
Cache::connect($options)->set('name','value',3600);
Cache::connect($options)->get('name');

If you want to return the handle of the current cache type object, you can use

// 获取Redis对象 进行额外方法调用
Cache::store('redis')->handler();

Customized driver

If you need to customize the cache driver, you need to inherit think\cache\Driver class, and implements think\contract\CacheHandlerInterface interface.

interface CacheHandlerInterface
{
    /**
     * 判断缓存
     * @access public
     * @param  string $name 缓存变量名
     * @return bool
     */
    public function has($name): bool;

    /**
     * 读取缓存
     * @access public
     * @param  string $name 缓存变量名
     * @param  mixed  $default 默认值
     * @return mixed
     */
    public function get($name, $default = false);

    /**
     * 写入缓存
     * @access public
     * @param  string            $name 缓存变量名
     * @param  mixed             $value  存储数据
     * @param  integer|\DateTime $expire  有效时间(秒)
     * @return bool
     */
    public function set($name, $value, $expire = null): bool;

    /**
     * 自增缓存(针对数值缓存)
     * @access public
     * @param  string    $name 缓存变量名
     * @param  int       $step 步长
     * @return false|int
     */
    public function inc(string $name, int $step = 1);

    /**
     * 自减缓存(针对数值缓存)
     * @access public
     * @param  string    $name 缓存变量名
     * @param  int       $step 步长
     * @return false|int
     */
    public function dec(string $name, int $step = 1);

    /**
     * 删除缓存
     * @access public
     * @param  string $name 缓存变量名
     * @return bool
     */
    public function delete($name): bool;

    /**
     * 清除缓存
     * @access public
     * @return bool
     */
    public function clear(): bool;

}