Is there a way to inject the EntityManager into the service
When used, Symfony 3.3
I declare a service like this:
class TheService implements ContainerAwareInterface
{
use ContainerAwareTrait;
...
}
Inside every activity where I need an EntityManager, I get it from the container:
$em = $this->container->get('doctrine.orm.entity_manager');
This is a little annoying, so I'm curious if Symfony has anything that acts like EntityManagerAwareInterface
.
source to share
Traditionally, you would create a new service definition in your file services.yml
to set the entity manager as an argument to your constructor
app.the_service:
class: AppBundle\Services\TheService
arguments: ['@doctrine.orm.entity_manager']
Most recently, with the release of symfony 3.3, the default symfony-standard-edition changed its default file to services.yml
use autowire
and added all the classes in AppBundle
for maintenance. This removes the need to add a personalized service and using a type hint in your constructor will automatically inject the correct service.
Your class of service will look like this
use Doctrine\ORM\EntityManagerInterface
class TheService
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
// ...
}
For more information on automatically detecting service dependencies, see https://symfony.com/doc/current/service_container/autowiring.html
A new default config file services.yml
is available here: https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml
source to share