Last active
August 25, 2017 10:37
-
-
Save vasildakov-zz/4d63cdbbf440689a0828dff7d329f25b to your computer and use it in GitHub Desktop.
Caching
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 | |
class CachedSkuRepository implements SkuRepositoryInterface | |
{ | |
private $repository; | |
private $cache; | |
public function __construct( | |
SkuRepositoryInterface $repository, | |
CacheItemPoolInterface $cache | |
) { | |
$this->repository = $repository; | |
$this->cache = $cache; | |
} | |
public function find($id) | |
{ | |
$item = $this->cache->getItem((string)$id); | |
if (!$item->isHit()) { | |
$sku = $this->repository->find($id); | |
$item->set($sku); | |
$this->cache->save($item); | |
} | |
return $item->get(); | |
} | |
public function persist($entity) | |
{ | |
// persist | |
$this->repository->persist($entity); | |
// delete cache if exist | |
$key = (string)$entity->getId(); | |
if( $this->cache->hasItem($key)) { | |
$this->cache->deleteItem($key); | |
} | |
} | |
} |
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 | |
class DoctrineSkuRepository implements SkuRepositoryInterface | |
{ | |
private $em; | |
public function __construct(EntityManager $em) | |
{ | |
$this->em = $em; | |
} | |
public function find($id) | |
{ | |
return $this->em->getRepository(SkuRepository::class)->find($id); | |
} | |
public function persist($entity) | |
{ | |
$this->em->persist($entity); | |
} | |
} |
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 | |
interface SkuRepositoryInterface | |
{ | |
public function persist(Sku $entity); | |
public function find($id); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment