首页 文章

如何在Symfony中的Subscriber中获取entityManager

提问于
浏览
0

我使用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
    }
}

是否可以在这里获得实体经理?

在创建Product之后,我需要创建另一个实体

1 回答

  • 1

    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'
    

相关问题