1 | <?php |
||
15 | class CachedProductRepository implements ProductRepositoryInterface |
||
16 | { |
||
17 | /** |
||
18 | * @var CacheItemPoolInterface |
||
19 | */ |
||
20 | private $cache; |
||
21 | /** |
||
22 | * @var ProductRepository |
||
23 | */ |
||
24 | private $productRepository; |
||
25 | |||
26 | /** |
||
27 | * Creates a new CachedProductRepository instance. |
||
28 | * |
||
29 | * @param CacheItemPoolInterface $cache A cache backend for storing the results |
||
30 | * @param ProductRepository $productRepository A product repository for reading and writing product data |
||
31 | * |
||
32 | */ |
||
33 | 2 | public function __construct(CacheItemPoolInterface $cache, ProductRepository $productRepository) |
|
38 | |||
39 | /** |
||
40 | * Get all products |
||
41 | * |
||
42 | * @return Product[] |
||
43 | * |
||
44 | * @throws RepositoryException If fetching the products failed |
||
45 | */ |
||
46 | 2 | public function getProducts() |
|
47 | { |
||
48 | 2 | $cacheKey = "products"; |
|
49 | 2 | if ($this->cache->hasItem($cacheKey)) { |
|
50 | |||
51 | // return from cache |
||
52 | 1 | $cacheItem = $this->cache->getItem($cacheKey); |
|
53 | 1 | $cachedProducts = $cacheItem->get(); |
|
54 | 1 | return $cachedProducts; |
|
55 | } |
||
56 | |||
57 | 1 | $products = $this->productRepository->getProducts(); |
|
58 | |||
59 | // save to cache |
||
60 | 1 | $cacheItem = $this->cache->getItem($cacheKey); |
|
61 | 1 | $cacheItem->set($products); |
|
62 | |||
63 | 1 | return $products; |
|
64 | } |
||
65 | |||
66 | public function getById(string $id) |
||
70 | |||
71 | public function add(Product $product) |
||
75 | |||
76 | public function remove(Product $product) |
||
80 | } |