purplehaze
purplehaze

Reputation: 29

Use entity manager in service

Is there a way to access an entity manager in a service ? Although I think I have to use a dependency injection, I can't find anything in the symfony documentation. I'm using symfony 4.

Upvotes: 0

Views: 819

Answers (4)

Akhmed
Akhmed

Reputation: 1179

Here is example of simple class with entity manager injected, that you can register as service:

namespace My\AppBundle;

use Doctrine\ORM\EntityManagerInterface;

class YourServiceName
{
    /**
     * @var EntityManagetInterface
     */
    private $em;

    public function __construct(EntityManagerInterface $em) : void
    {
        $this->em = $em;
    }

}

And in services.yml:

services:
    your.service.name:
        class: My\AppBundle\YourServiceName
        arguments: [ @doctrine.orm.default_entity_manager]

Upvotes: 1

Youssef Saoubou
Youssef Saoubou

Reputation: 591

Use the EntityManagerInterface to your service and check the autoWiring or you will need to inject it

Upvotes: 0

Magnesium
Magnesium

Reputation: 617

Yes you can,

use Doctrine\Common\Persistence\ObjectManager;

public function __construct(ObjectManager $manager)
{
    $this->manager = manager;
}

Upvotes: 0

Kamil Adryjanek
Kamil Adryjanek

Reputation: 3338

Just inject it into the constructor:

use Doctrine\ORM\EntityManagerInterface

class YourService
{
    private $em;

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

    // ...
}

Thanks to autowiring no extra configuration is required.

Upvotes: 1

Related Questions