Avoiding container lines in dependency injection in symfony

New for symfony and php. I was able to successfully define the service and inject the doctrine entity manager into it. It works fine, but during initialization, I have to pass a string containing the service name like this:

    $eRep = $this->container->get('employee_repository');

      

Can this be avoided? Could this be converted to something more elegant like

   $eRep = $this->container->getEmployeeRepository();

      

The service is defined as:

services:
employee_repository:
    class: AppBundle\Repository\EmployeeRepository
    arguments: [@doctrine.orm.entity_manager]               

      

Sorry for the question about the nob. EDIT

Can I access the service container inside another class, say EmployeeEnvelope, and call the following:

class EmployeeEnvelope{

    public function getEmployeeRepository()
    {               
        return $this->container->get('employee_repository');
    } 
}

      

+3


source to share


1 answer


If you are requesting a service from a controller, you can configure your controller as a service. Then you can push the repository service to employees using dependency injection.

This way you won't have a line reference in the controller, but in the config.



http://symfony.com/doc/current/cookbook/controller/service.html

+2


source







All Articles