我使用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 回答
Symfony允许(并建议)注入dependencies in services .
我们向订阅者添加一个构造函数,以便注入Doctrine并通过
$this->entityManager
使其可访问:如果启用了autowiring,您将无需执行任何其他操作,该服务将自动实例化 .
如果没有,你必须declare the service: