chadicus / psr-cache-mongodb
v1.0.0
2018-01-07 03:21 UTC
Requires
- php: ^7.0
- chadicus/psr-cache-helper: ^0.2.1
- mongodb/mongodb: ^1.1
- psr/simple-cache: ^1.0
Requires (Dev)
- chadicus/coding-standard: ^1.2
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^6.1
This package is auto-updated.
Last update: 2022-09-19 16:14:22 UTC
README
PSR-16 SimpleCache 实现,使用 MongoDB
要求
需要 PHP 7.0(或更高版本)。
Composer
要添加库作为本地、项目级别的依赖,请使用 Composer!只需将 subjective-php/psr-cache-mongodb
添加到项目的 composer.json
文件中,例如
composer require subjective-php/psr-cache-mongodb
联系方式
开发者可以通过以下方式联系
项目构建
检出代码后,在您的 PATH 中获取 Composer 并运行
composer install ./vendor/bin/phpunit
使用 Guzzle 客户端缓存 PSR-7 响应消息的示例
以下是一个在 mongo 中缓存 GET 请求响应的简化示例。
<?php use Chadicus\Psr\SimplCache\SerializerInterface; use Chadicus\Psr\SimplCache\MongoCache; use GuzzleHttp\Psr7; use MongoDB\Client; use Psr\SimpleCache\InvalidArgumentException; /** * Provides serialization from mongo documents to PSR-7 response objects. */ final class Psr7Serializer implements SerializerInterface { /** * Unserializes cached data into the original state. * * @param array $data The data to unserialize. * * @return Diactoros\Response */ public function unserialize(array $data) { return new Psr7\Response( $data['statusCode'], $data['headers'], $data['body'], $data['protocolVersion'], $data['reasonPhrase'] ); } /** * Serializes the given data for storage in caching. * * @param mixed $value The data to serialize for caching. * * @return array The result of serializing the given $data. * * @throws InvalidArgumentException Thrown if the given value is not a PSR-7 Response instance. */ public function serialize($value) : array { if (!is_a($value, '\\Psr\\Http\\Message\\ResponseInterface')) { throw new class('$value was not a PSR-7 Response') extends \Exception implements InvalidArgumentException { }; } return [ 'statusCode' => $value->getStatusCode(), 'headers' => $value->getHeaders(), 'body' => (string)$value->getBody(), 'protocolVersion' => $value->getProtocolVersion(), 'reasonPhrase' => $value->getReasonPhrase(), ]; } } //create the mongo collection $collection = (new Client('mongodb://locathost:27017'))->selectDatabase('psr')->selectCollection('cache'); //Set a TTL index on the expires field $collection->createIndex(['expires' => 1], ['expireAfterSeconds' => 0]); $cache = new MongoCache($collection, new Psr7Serializer()); // Use the cache when sending guzzle requests //Only caching GET responses if ($request->getMethod() === 'GET') { $key = (string)$request->getUri(); $response = $cache->get($key); if ($response === null) { $response = $guzzleClient->send($request); //Add to cache if valid Expires header if ($response->hasHeader('Expires')) { $expires = strtotime($response->getHeader('Expires')[0]); $cache->set($key, $response, $expires - time()); } } } else { $response = $guzzleClient->send($request); }