我怎样才能在 Symfony 的订阅者中获得 entityManager

How can i get entityManager inside Subscriber in Symfony

我使用 Api 平台。我有订阅者

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
    }
}

这里能招到实体经理吗?

我需要在创建产品后创建另一个实体

Symfony 允许(并推荐)注入 dependencies in services

我们向订阅者添加一个构造函数以注入 Doctrine 并使其可访问 $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();
    }

如果启用autowiring,您将无事可做,服务将自动实例化。

如果没有,您将不得不 declare the service:

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