Guest User

Untitled

a guest
Oct 2nd, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. <?php
  2.  
  3. namespace src\Integration;
  4.  
  5. class DataProvider
  6. {
  7. private $host;
  8. private $user;
  9. private $password;
  10.  
  11. /**
  12. * @param $host
  13. * @param $user
  14. * @param $password
  15. */
  16. public function __construct($host, $user, $password)
  17. {
  18. $this->host = $host;
  19. $this->user = $user;
  20. $this->password = $password;
  21. }
  22.  
  23. /**
  24. * @param array $request
  25. *
  26. * @return array
  27. */
  28. public function get(array $request)
  29. {
  30. // returns a response from external service
  31. }
  32. }
  33.  
  34. ?>
  35.  
  36. <?php
  37.  
  38. namespace src\Decorator;
  39.  
  40. use DateTime;
  41. use Exception;
  42. use Psr\Cache\CacheItemPoolInterface;
  43. use Psr\Log\LoggerInterface;
  44. use src\Integration\DataProvider;
  45.  
  46. class DecoratorManager extends DataProvider
  47. {
  48. private $cache;
  49. private $logger;
  50.  
  51. /**
  52. * @param string $host
  53. * @param string $user
  54. * @param string $password
  55. * @param CacheItemPoolInterface $cache
  56. */
  57. public function __construct($host, $user, $password, CacheItemPoolInterface $cache, LoggerInterface $logger = null)
  58. {
  59. parent::__construct($host, $user, $password);
  60. $this->cache = $cache;
  61.  
  62. // Просто дополнительное удобство, что $logger можно сразу передать в конструктор без отдельного вызова setLogger
  63. // При этом он остается опциональным
  64. if ($logger instanceof LoggerInterface)
  65. $this->logger = $logger;
  66. }
  67.  
  68. public function setLogger(LoggerInterface $logger)
  69. {
  70. $this->logger = $logger;
  71. }
  72.  
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function get(array $request)
  77. {
  78. try {
  79. $cacheKey = $this->getCacheKey($request);
  80. $cacheItem = $this->cache->getItem($cacheKey);
  81. if ($cacheItem->isHit()) {
  82. return $cacheItem->get();
  83. }
  84. }
  85. catch (Exception $e) {
  86. if ($this->logger instanceof LoggerInterface)
  87. $this->logger->error('Cache error'); // заменил critical на error
  88. }
  89.  
  90.  
  91. try {
  92. $result = parent::get($request);
  93. }
  94. catch {
  95. if ($this->logger instanceof LoggerInterface)
  96. $this->logger->critical('External data source error');
  97.  
  98. return [];
  99. }
  100.  
  101. $cacheItem
  102. ->set($result)
  103. ->expiresAt(
  104. (new DateTime())->modify('+1 day')
  105. );
  106.  
  107. return $result;
  108. }
  109.  
  110. private function getCacheKey(array $request)
  111. {
  112. return json_encode($request);
  113. }
  114. }
  115.  
  116. ?>
Add Comment
Please, Sign In to add comment