benjamindean / one-line-apc
一个简单的APC和APCu包装类,可以在一行代码内设置和获取缓存数据。
v0.1.1
2016-04-09 09:25 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-20 18:28:48 UTC
README
一个简单的APC和APCu包装类,可以在一行代码内从回调或变量中设置和获取缓存数据。
需求
- PHP 5.3或更高版本
php-apc
扩展已安装
安装
使用Composer安装
$ composer require benjamindean/one-line-apc
用法
require 'vendor/autoload.php'; $cache = new OneLineAPC();
默认情况下,这个类使用APC。要使用APCu,只需在实例化类时传入它即可
$cache = new OneLineAPC('apcu');
默认TTL是79200(22小时)。要更改它,请调用setTtl
方法
$cache->setTtl(3600);
或者,将TTL作为最后参数分别指定给setCache
或cached
方法
$cache->setCache($dataToCache, 'key', 3600);
缓存
主要且最重要的方法是cached
(我创建这个类的理由)
$cache->cached('key', 'functionName');
functionName
是代码中某个需要缓存数据的函数的名称。任何变量、整数或字符串都可以。您也可以在这里传递作为第三个参数的函数参数。
如果您的函数位于某个类中,请将其作为包含对象和函数名的数组传递
$cache->cached('key', array($obj, 'functionName'));
有关回调的更多信息,请参阅此处。
示例
类方法
class ReturnData { public function fetchData($url) { return file_get_contents($url); } } $obj = new ReturnData(); $apc = new OneLineAPC(); $apc->setTtl(3600); return $apc->cached('key', array($obj, 'fetchData'), array('http://example.com/'));
函数
function fetchData($url) { return file_get_contents($url); } $apc = new OneLineAPC(); $apc->setTtl(3600); return $apc->cached('key', 'fetchData', array('http://example.com/'));
变量
$something = 'Data to be cached'; $apc = new OneLineAPC(); return $apc->cached('key', $something, false, 3600);
注意
如果未加载apc
或apcu
,则此类将生成"Notice",而不是"Fatal Error"。