snicholson/slimfilecache

基于文件的缓存中间件,适用于slim框架(3.0)

1.0.3 2017-05-23 18:12 UTC

This package is auto-updated.

Last update: 2024-09-25 05:39:40 UTC


README

这是一个基于文件的缓存中间件,适用于slim框架(3.0)。缓存是一个简单的基于文件的缓存,我需要一个针对特定情况的东西,在这种情况下,我有许多外部API请求(基本上是一个API聚合器)需要执行,并且在给定的时间段内,它们总是会给出相同的输出。我不需要数据库或任何花哨的东西,并且对性能也不太关心。因此,基于文件的缓存非常有意义。

安装

通过composer进行安装

composer require snicholson/slimfilecache "~1.0"

要求

此中间件与slim 3.0 Release Candidate版本兼容。

设置

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

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

// Add file cache middleware
$cache = new \SNicholson\SlimFileCache\Cache($slim);
$slim->add($cache);

使用方法

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

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

// Add file cache middleware
$cache = new \SNicholson\SlimFileCache\Cache($slim, 'relate/path/to/cache/directory');
$slim->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)
$slim->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());

缓存还有一些其他简单的方法。它们基本上就是它们名字所暗示的

$cache = new \SNicholson\SlimFileCache\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');