Skip to content

Entity Manager

The entity manager of Muprh is a proxy of the Doctrine's entity manager. It gives you an easy way to create, update and delete an entity and dispatches events easy to subscribe to.

Implementation

Entities must implements App\Core\Entity\EntityInterface.

src/Entity/MyEntity.php
namespace App\Entity;

use App\Repository\MyEntityRepository;
use Doctrine\ORM\Mapping as ORM;
use App\Core\Entity\EntityInterface;

#[ORM\Entity(repositoryClass: MyEntityRepository::class)]
class MyEntity implements EntityInterface
{
    // ...
}

Usage

There are 2 entity managers which are services:

  • App\Core\Manager\EntityManager used for all entities
  • App\Core\Manager\TranslatableEntityManager used for translatable entities
src/Controller/FooController.php
namespace App\Controller;

use App\Core\Manager\EntityManager
use App\Entity\MyEntity;
use Symfony\Component\HttpFoundation\Response;

class FooController
{
    public function foo(EntityManager $entityManager): Response
    {
        $myEntity = new MyEntity();

        // Creates an entity
        $entityManager->create($myEntity);

        // Updates an entity
        $entityManager->update($myEntity);

        // Deletes an entity
        $entityManager->delete($myEntity);

        // ...
    }
}

Events

Events are dispatched before and after creation, update and deletion. All entities of Muprh use the entity manager.

src/EventSubscriber/MyEntityEventSubscriber.php
namespace App\EventSubscriber;

use App\Core\Entity\EntityInterface;
use App\Core\Event\EntityManager\EntityManagerEvent;
use App\Core\EventSubscriber\EntityManagerEventSubscriber;
use App\Entity\MyEntity;

class MyEntityEventSubscriber extends EntityManagerEventSubscriber
{
    public function supports(EntityInterface $entity): bool
    {
        return $entity instanceof MyEntity;
    }

    public function onCreate(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }

    public function onUpdate(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }

    public function onDelete(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }

    public function onPreCreate(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }

    public function onPreUpdate(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }

    public function onPreDelete(EntityManagerEvent $event)
    {
        if (!$this->supports($event->getEntity())) {
            return;
        }

        // ...
    }
}