uea/slimcache

slim 3 PHP框架的基于文件的缓存系统。

dev-master 2017-02-23 22:47 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:53:44 UTC


README

slim 3 PHP框架的基于文件的缓存系统。

这个缓存是一个简单的基于文件的缓存,我在一个非常特定的情况下需要它,那时我有很多外部API请求(本质上是一个API聚合器),在给定的时间段内它们总是给出相同的输出。

我不需要数据库或任何复杂的东西,对性能也不是很关心。

所以基于文件的缓存非常合理。

安装

安装通过composer完成

composer require uea/slimcache dev-master

要求

此中间件与slim 3.0兼容

设置

中间件符合slim的正常注入要求。下面的例子是缓存的基本设置。一旦实施,它将自动加载当前正在调用的路由的任何活动缓存记录,并停止应用程序的执行。

//Start up a new slim app
$app = new App($container);

// Add file cache middleware
$cache = new \UEA\SlimCache\Cache($app);
$app->add($cache);

使用方法

要使用缓存,您只需在返回之前缓存您路由的输出。add方法接受3个参数,第一个是路由名称。第二个是内容,第三个参数是响应代码状态(例如200)以及缓存持续时间(以秒为单位)。默认长度为1小时。缓存的第二个参数是存储缓存文件的目录。目录必须可以被网络用户写入。

//Start up a new slim app
$app = new App($container);

// Add file cache middleware
$cache = new \UEA\SlimCache\Cache($app, 'path/to/cacheDirectory');
$app->add($cache);

//Configure the "foo" route and cache the output
$slim->get('/foo', function(\Slim\Http\Request $request, \Slim\Http\Response $response, $args) use ($cache) {
$response = 'foo response string';
$cache->add('/foo', $response);
return $response;
}
);

或者,您可以通过在运行slim应用后放置以下行来告诉缓存存储所有被调用的路由:

//Run the slim app (like normal)
$app->run();

//Place the global cache afterwards, the next request at this route will be cached
$cache->add($slim->request->getUri()->getPath(), $slim->response->getBody()->__toString());

缓存还有一些其他简单的方法。它们分别是flush、get、remove。它们基本上做了它们名字所暗示的事情。

$cache = new \UEA\SlimCache\Cache($slim)

//Flush removes all entries
$cache->flush();

//Remove a single cache entry
$cache->remove('/foo');

//Get returns what is stored in the cache
$response = $cache->get('/foo');