Reputation: 29
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
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
Reputation: 591
Use the EntityManagerInterface to your service and check the autoWiring or you will need to inject it
Upvotes: 0
Reputation: 617
Yes you can,
use Doctrine\Common\Persistence\ObjectManager;
public function __construct(ObjectManager $manager)
{
$this->manager = manager;
}
Upvotes: 0
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