我如何在 Symfony 的订阅者中获取 entityManager

Bil*_*ard 1 php symfony api-platform.com

我使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以在这里找到实体经理?

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

A.L*_*A.L 5

Symfony 允许(并推荐)在 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();
    }
Run Code Online (Sandbox Code Playgroud)

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

如果没有,您必须声明服务

App\EventSubscriber\Api\ProductCreateSubscriber:
    arguments:
        - '@doctrine.orm.entity_manager'
Run Code Online (Sandbox Code Playgroud)