说明
在使用php-cache之前,必须先连接缓存(非每次都需要,只需要连接一次。如果后面想切换缓存方式重新调用connect或者提前初始化预存好想使用的缓存方式)。
语法
Cache::connect(array $options = [],boolean $forceInstance = false);
示例代码
use renpengpeng\Cache;// 初始化File的缓存方式// connect(array $options,boolean $forceInstance=false)$instance = Cache::connect(['type' => 'file','file' => ['cache_dir' => realpath(__DIR__).DIRECTORY_SEPARATOR.'cache']]);// 操作缓存Cache::set('test','test');// 等效于$instance->set('test',test);
$options
参数概览
$options = ['type' => 'File', // 缓存驱动类型(详见下方驱动类型)'prefix' => 'cache_', // 缓存前缀'expire' => 0, // 有效期/*** File 驱动配置*/'file' => ['cache_dir' => null,],/*** Redis 服务器配置*/'redis' => ['host' => '127.0.0.1','port' => 6379,'password' => '','select' => '','timeout' => 0,'pconnect' => false],/*** Memcache 服务器配置*/'memcache' => ['host' => '127.0.0.1','port' => 11211,'timeout' => 1,'pconnect' => false]];
缓存驱动类型(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。
