Billizzard
Billizzard

Reputation: 518

How can i get entityManager inside Subscriber in Symfony

I use Api Platform. I have subscriber

namespace App\EventSubscriber\Api;

use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Product;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class ProductCreateSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['createHost', EventPriorities::POST_WRITE],
        ];
    }

    public function createHost(GetResponseForControllerResultEvent $event)
    {
        $product = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$product instanceof Product || Request::METHOD_POST !== $method) {
            return;
        }

        I NEED ENTITY MANAGER HERE
    }
}

Is it possible to get a entity manager here?

I need create another entity, after creating Product

Upvotes: 1

Views: 3235

Answers (1)

A.L
A.L

Reputation: 10513

Symfony allow (and recommend) to inject dependencies in services.

We add a constructor to the subscriber in order to inject Doctrine and make it accessible though $this->entityManager:

use Doctrine\ORM\EntityManagerInterface;

final class ProductCreateSubscriber implements EventSubscriberInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    public function __construct(
        EntityManagerInterface $entityManager
    ) {
        $this->entityManager = $entityManager;
    }

    public function createHost(GetResponseForControllerResultEvent $event)
    {
        $product = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if (!$product instanceof Product || Request::METHOD_POST !== $method) {
            return;
        }

        // You can access to the entity manager
        $this->entityManager->persist($myObject);
        $this->entityManager->flush();
    }

If autowiring is enabled, you'll have nothing else to do, the service will be instantiated automatically.

If not, you'll have to declare the service:

App\EventSubscriber\Api\ProductCreateSubscriber:
    arguments:
        - '@doctrine.orm.entity_manager'

Upvotes: 7

Related Questions