我如何在Symfony中的订户内获取EntityManager

时间:2018-12-09 13:52:03

标签: 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
    }
}

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

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

1 个答案:

答案 0 :(得分:1)

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

我们向订户添加了一个构造函数,以便注入学说并使其可通过$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'