Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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);
- }
- }
- ?>
Add Comment
Please, Sign In to add comment