Created
May 27, 2021 14:46
-
-
Save amanangira/8829305cc4cb277eb391130d568c2a42 to your computer and use it in GitHub Desktop.
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 | |
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