说明

在使用php-cache之前,必须先连接缓存(非每次都需要,只需要连接一次。如果后面想切换缓存方式重新调用connect或者提前初始化预存好想使用的缓存方式)。

语法

  1. Cache::connect(array $options = [],boolean $forceInstance = false);

示例代码

  1. use renpengpeng\Cache;
  2. // 初始化File的缓存方式
  3. // connect(array $options,boolean $forceInstance=false)
  4. $instance = Cache::connect([
  5. 'type' => 'file',
  6. 'file' => [
  7. 'cache_dir' => realpath(__DIR__).DIRECTORY_SEPARATOR.'cache'
  8. ]
  9. ]);
  10. // 操作缓存
  11. Cache::set('test','test');
  12. // 等效于
  13. $instance->set('test',test);

$options

参数概览

  1. $options = [
  2. 'type' => 'File', // 缓存驱动类型(详见下方驱动类型)
  3. 'prefix' => 'cache_', // 缓存前缀
  4. 'expire' => 0, // 有效期
  5. /**
  6. * File 驱动配置
  7. */
  8. 'file' => [
  9. 'cache_dir' => null,
  10. ],
  11. /**
  12. * Redis 服务器配置
  13. */
  14. 'redis' => [
  15. 'host' => '127.0.0.1',
  16. 'port' => 6379,
  17. 'password' => '',
  18. 'select' => '',
  19. 'timeout' => 0,
  20. 'pconnect' => false
  21. ],
  22. /**
  23. * Memcache 服务器配置
  24. */
  25. 'memcache' => [
  26. 'host' => '127.0.0.1',
  27. 'port' => 11211,
  28. 'timeout' => 1,
  29. 'pconnect' => false
  30. ]
  31. ];

缓存驱动类型(type)

目前php-cache支持以下几种驱动方式的缓存,默认为File(文件缓存),可以在type中指定以下几种(指定时不区分大小写)

驱动值 说明
File 文件缓存
Redis Redis缓存
Memcache Memcache缓存(非Memcached)
Apcu Apcu缓存
Yac Yac缓存

缓存前缀(prefix)

在缓存时,可指定默认缓存前缀,防止与其他缓存产生key的冲突,默认为:cache_

缓存有效期(expire)

默认有效期为:0,表示永久缓存。可指定任意有效期(秒)。

File 驱动配置

参数 参数类型 说明
cache_dir string 缓存目录,需指定绝对路径,如/www/wwwroot/….

Redis 服务器器配置

参数 参数类型 说明
host string 主机地址,默认127.0.0.1
port integer 端口,默认6379
password string Redis密码,默认为空
select string 数据库选择,默认为空
timeout integer 链接超时,默认为0
pconnect boolean 是否为长链接,默认为false

Memcache 服务器配置

参数 参数类型 说明
host string 主机地址,默认127.0.0.1
port integer 端口,默认11211
timeout integer 链接超时,默认为1
pconnect boolean 是否为长链接,默认为false

$forceInstance

在实例化缓存的时候,会给每个链接根据参数生成一个name,如果相同的参数实例化过会存入缓存池中,下次调用将直接从池里取而不会反复实例化。

此参数默认为:false,表示不强制实例化,如果需要强制实例化时,请指定true。