Created
October 2, 2018 08:47
-
-
Save beeryukov/3992778057d31b68bf2e2f22172a6926 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace src\Integration; | |
class DataProvider | |
{ | |
private $host; | |
private $user; | |
private $password; | |
/** | |
* @param $host | |
* @param $user | |
* @param $password | |
*/ | |
public function __construct($host, $user, $password) | |
{ | |
$this->host = $host; | |
$this->user = $user; | |
$this->password = $password; | |
} | |
/** | |
* @param array $request | |
* | |
* @return array | |
*/ | |
public function get(array $request) | |
{ | |
// returns a response from external service | |
} | |
} | |
?> | |
<?php | |
namespace src\Decorator; | |
use DateTime; | |
use Exception; | |
use Psr\Cache\CacheItemPoolInterface; | |
use Psr\Log\LoggerInterface; | |
use src\Integration\DataProvider; | |
class DecoratorManager extends DataProvider | |
{ | |
private $cache; | |
private $logger; | |
/** | |
* @param string $host | |
* @param string $user | |
* @param string $password | |
* @param CacheItemPoolInterface $cache | |
*/ | |
public function __construct($host, $user, $password, CacheItemPoolInterface $cache, LoggerInterface $logger = null) | |
{ | |
parent::__construct($host, $user, $password); | |
$this->cache = $cache; | |
// Просто дополнительное удобство, что $logger можно сразу передать в конструктор без отдельного вызова setLogger | |
// При этом он остается опциональным | |
if ($logger instanceof LoggerInterface) | |
$this->logger = $logger; | |
} | |
public function setLogger(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function get(array $request) | |
{ | |
try { | |
$cacheKey = $this->getCacheKey($request); | |
$cacheItem = $this->cache->getItem($cacheKey); | |
if ($cacheItem->isHit()) { | |
return $cacheItem->get(); | |
} | |
} | |
catch (Exception $e) { | |
if ($this->logger instanceof LoggerInterface) | |
$this->logger->error('Cache error'); // заменил critical на error | |
} | |
try { | |
$result = parent::get($request); | |
} | |
catch { | |
if ($this->logger instanceof LoggerInterface) | |
$this->logger->critical('External data source error'); | |
return []; | |
} | |
$cacheItem | |
->set($result) | |
->expiresAt( | |
(new DateTime())->modify('+1 day') | |
); | |
return $result; | |
} | |
private function getCacheKey(array $request) | |
{ | |
return json_encode($request); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment