Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace src\Integration;
- interface DataProviderInterface
- {
- public function get(array $request) : array;
- }
- <?php
- declare(strict_types=1);
- namespace src\Integration;
- class DataProvider implements DataProviderInterface
- {
- protected $host;
- protected $user;
- protected $password;
- /**
- * @param $host
- * @param $user
- * @param $password
- */
- public function __construct(string $host, string $user, string $password)
- {
- $this->host = $host;
- $this->user = $user;
- $this->password = $password;
- }
- /**
- * @param array $request
- *
- * @return array
- */
- public function get(array $request) : array
- {
- // returns a response from external service
- }
- }
- <?php
- declare(strict_types=1);
- namespace src\Decorator;
- use Exception;
- use Psr\Cache\CacheItemPoolInterface;
- use Psr\Log\LoggerInterface;
- use src\Integration\DataProviderInterface;
- class DataProviderCachingDecorator implements DataProviderInterface
- {
- protected $provider;
- protected $cache;
- protected $logger;
- public function __construct(DataProviderInterface $provider, CacheItemPoolInterface $cache)
- {
- $this->provider = $provider;
- $this->cache = $cache;
- }
- public function setLogger(LoggerInterface $logger)
- {
- $this->logger = $logger;
- }
- public function get(array $request) : array
- {
- $result = [];
- try {
- $cacheKey = $this->getCacheKey($request);
- $cacheItem = $this->cache->getItem($cacheKey);
- if ($cacheItem->isHit()) {
- $result = $cacheItem->get();
- } else {
- $result = $this->provider->get($request);
- $cacheItem
- ->set($result)
- ->expiresAfter(3600 * 24); // expires after a day
- }
- } catch (Exception $e) {
- if ($this->logger) {
- $this->logger->critical(implode(', ', [ __FILE__, __LINE__, $e->getMessage() ]));
- } else {
- throw $e;
- }
- }
- return $result;
- }
- public function getCacheKey(array $input)
- {
- return md5(json_encode($input));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement