Is there a way to inject EntityManager into a service Is there a way to inject EntityManager into a service symfony symfony

Is there a way to inject EntityManager into a service


Traditionally, you would have created a new service definition in your services.yml file set the entity manager as argument to your constructor

app.the_service:    class: AppBundle\Services\TheService    arguments: ['@doctrine.orm.entity_manager']

More recently, with the release of symfony 3.3, the default symfony-standard-edition changed their default services.yml file to default to using autowire and add all classes in the AppBundle to be services. This removes the need for adding the custom service and using a type hint in your constructor will automatically inject the right service.

Your service class would then look like the following

use Doctrine\ORM\EntityManagerInterfaceclass TheService{    private $em;    public function __construct(EntityManagerInterface $em)    {        $this->em = $em;    }    // ...}

For more information about automatically defining service dependencies, see https://symfony.com/doc/current/service_container/autowiring.html

The new default services.yml configuration file is available here: https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml


Sometimes I inject the EM into a service on the container like this in services.yml:

 application.the.service:      class: path\to\te\Service      arguments:        entityManager: '@doctrine.orm.entity_manager'

And then on the service class get it on the __construct method.Hope it helps.


I ran into the same issue and solved it by editing the migration code.

I replaced

$this->addSql('ALTER TABLE user ADD COLUMN name VARCHAR(255) NOT NULL');

by

$this->addSql('ALTER TABLE user ADD COLUMN name VARCHAR(255) NOT NULL DEFAULT "-"');

I don't know why bin/console make:entity doesn't prompt us to provide a default in those cases. Django does it and it works well.