Skip to content

Instantly share code, notes, and snippets.

@amanangira
Created May 27, 2021 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amanangira/8829305cc4cb277eb391130d568c2a42 to your computer and use it in GitHub Desktop.
Save amanangira/8829305cc4cb277eb391130d568c2a42 to your computer and use it in GitHub Desktop.
<?php
namespace App\AppBundle\Creator;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* {@inheritdoc}
*/
abstract class AbstractOrmEntityCreator implements EntityCreatorInterface, EventSubscriberInterface
{
/** @var EventDispatcherInterface */
protected $eventDispatcher;
/** @var EntityManager */
protected $entityManager;
/**
* @param EventDispatcherInterface $eventDispatcher
* @param EntityManager $entityManager
*/
public function __construct(
EventDispatcherInterface $eventDispatcher,
EntityManager $entityManager
) {
$this->eventDispatcher = $eventDispatcher;
$this->entityManager = $entityManager;
}
/**
* {@inheritdoc}
*/
public function create($entity)
{
$this->entityManager->persist($entity);
$this->entityManager->flush();
return $entity;
}
/**
* {@inheritdoc}
*/
public function update($entity)
{
$this->entityManager->persist($entity);
$this->entityManager->flush();
return $entity;
}
/**
* {@inheritdoc}
*/
public function delete($entity)
{
$this->entityManager->remove($entity);
$this->entityManager->flush();
}
/**
* Compute entity change set
*
* @param object $entity
*
* @return array
*/
protected function getChangeSet($entity)
{
$uow = $this->entityManager->getUnitOfWork();
$uow->computeChangeSets();
return $uow->getEntityChangeSet($entity);
}
/** Event Subscribers */
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [ ];
}
}
class BankAccountCreator extends AbstractOrmEntityCreator
{
/**
* @param BankAccount $entity
*
* @return BankAccount
*/
public function create($entity)
{
$balance = $entity->balance;
$this->eventDispatcher->dispatch(
BankAccountPreCreateEvent::EVENT_NAME,
new BankAccountPreCreateEvent($entity)
);
$entity = parent::create($entity);
$this->eventDispatcher->dispatch(
BankAccountPostCreateEvent::EVENT_NAME,
new BankAccountPostCreateEvent($entity, $balance)
);
return $entity;
}
// Add more CRUD operations
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment