3

New to symfony and php. I was able to successfully define a service and inject the doctrine entity manager into it. It works fine but during the initialization I have to pass a string that contains the service name as follows:

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

Can this be avoided? Can 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]               

Apologies for the noob question. EDIT

Can I get access to a service container inside another class say EmployeeEnvelope and call as follows:

class EmployeeEnvelope{

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

1 Answer 1

2

If you're requesting the service from a controller, you can setup your controller to be a service too. Then you can pass the employee repository service to it using dependency injection.

That way you will not have the string reference in the controller, but in the configuration.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can I get access to the container in a generic PHP class? Please check my edits
There is no generic way to do it. It's not a good practice. If your class implements business logic you may consider making it a service and using dependency injection to provide it with other services it needs. Otherwise you may pass the empoyee entities it needs to that class in a constructor or with a set method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.