Skip to content

Instantly share code, notes, and snippets.

@woprrr
Created January 22, 2021 11:58
Show Gist options
  • Save woprrr/a86770d6d82a8189f69906eede17030e to your computer and use it in GitHub Desktop.
Save woprrr/a86770d6d82a8189f69906eede17030e to your computer and use it in GitHub Desktop.
Fast example of Symfony 4.* + Repository Service Decorator
<?php
namespace App\Repository;
use App\Entity\YourEntity;
use Doctrine\{Common\Collections\Criteria, ORM\QueryBuilder};
use Knp\Component\Pager\Pagination\PaginationInterface;
/**
* class BaseYourEntityRepositoryDecorator.
*
* @codeCoverageIgnore
*/
class BaseYourEntityRepositoryDecorator implements YourEntityRepositoryInterface
{
/**
* @var YourEntityRepositoryInterface
*/
private $yourEntityRepository;
/**
* AbstractBookRepositoryDecorator constructor.
*
* @param YourEntityRepositoryInterface $yourEntityRepository
*/
public function __construct(YourEntityRepositoryInterface $yourEntityRepository)
{
$this->yourEntityRepositoryDecorated = $yourEntityRepository;
}
/**
* {@inheritdoc}
*/
public function persist(YourEntity $yourEntity, bool $flush = false): void
{
$this->yourEntityRepositoryDecorated->persist($yourEntity, $flush);
/* XOR possibly ...
$this->yourEntityRepositoryDecorated->_em->persist($book);
if ($flush) {
$this->yourEntityRepositoryDecorated->_em->flush();
}
*/
}
}
App\Repository\YourEntitySaveEventDecorator:
decorates: App\Repository\YourEntityRepository
decoration_priority: 2
arguments:
- '@App\Repository\YourEntitySaveEventDecorator.inner'
<?php
namespace App\Repository;
use App\{YourDomain\Event\YourEntitySaved, Entity\YourEntity};
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
/**
* Class YourEntitySaveEventDecorator.
*
*/
final class YourEntitySaveEventDecorator extends BaseBookRepositoryDecorator
{
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* YourEntitySaveEventDecorator constructor.
*
* @param YourEntityRepositoryInterface $yourEntityRepository
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(YourEntityRepositoryInterface $yourEntityRepository, EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
parent::__construct($yourEntityRepository);
}
/**
* {@inheritDoc}
*/
public function persist(YourEntity $yourEntity, bool $flush = false): void
{
parent::persist($yourEntity, $flush);
$this->eventDispatcher->dispatch(new YourEntitySaved($yourEntity));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment