Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3925

Dependency Injections seems to create new doctrine instance, which causes an entity to be detached)

$
0
0

I've got two services, those get Doctrine injected via the constructor. When loading an entity in an EventListener and giving it ot service the entity is detached.

When im providing the DoctrineEntityManager from an EventListener to service, the entity is still managed.

class Listener implements EventSubscriberInterface
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var Service */
    private $service;

    /** @var EventDispatcherInterface */
    private $eventDispatcher;

    public function __construct(
        EntityManagerInterface $em,
        Service $service,
        EventDispatcherInterface $eventDispatcher
    ) {
        $this->em = $em;

        $this->eventDispatcher = $eventDispatcher;
        $this->service = $service;
    }


    public function listenerFunction(Event $event)
    {
        $user = $event->getEntity()->getUser();
        var_dump($this->em->contains($user)); // true

        $this->service->func($this->em, $user);
    }
}

class Service
{
    /** @var EventDispatcherInterface */
    private $eventDispatcher;

    public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher)
    {
        $this->em = $em;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function func($em, $user)
    {
        var_dump($this->em->contains($user)); // false 
        var_dump($em->contains($user)); // true
    }
}

the services yaml

services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: true

  App\Payment\Command\:
    resource: "%kernel.project_dir%/src/Payment/Command/*"
    tags:
      - { name: console.command }

  App\Payment\Service\:
    resource: "%kernel.project_dir%/src/Payment/Service/*"

  App\Payment\Controller\:
    resource: "%kernel.project_dir%/src/Payment/Controller/*"

  App\Payment\EventSubscriber\:
    resource: "%kernel.project_dir%/src/Payment/EventSubscriber/*"
    tags:
      - { name: kernel.event_subscriber }

The EntityManager in the service should contain the $user entity. Im thinking symfony is creating a second instance of the entitymanagerinterface here, but the says there is only one instance of each item (https://symfony.com/doc/current/service_container/shared.html)


Viewing all articles
Browse latest Browse all 3925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>