Skip to content

Instantly share code, notes, and snippets.

@vasildakov-zz
Last active August 25, 2017 10:37
Show Gist options
  • Save vasildakov-zz/4d63cdbbf440689a0828dff7d329f25b to your computer and use it in GitHub Desktop.
Save vasildakov-zz/4d63cdbbf440689a0828dff7d329f25b to your computer and use it in GitHub Desktop.
Caching
<?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);
}
}
}
<?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);
}
}
<?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