Я использую Api Platform. У меня есть подписчик
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 позволяют (и рекомендуют) вводить зависимости в услугах.
Мы добавляем конструктор к подписчику, чтобы внедрить 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();
}
Если автоматическое связывание включен, вам больше нечего делать, сервис будет создан автоматически.
Если нет, вам придется объявить услугу:
App\EventSubscriber\Api\ProductCreateSubscriber:
arguments:
- '@doctrine.orm.entity_manager'
Других решений пока нет …