Dependency Injection Through A Setter

- 1 answer

Does Laravel have the ability to introduce dependency through a method?
For example, I have a controller that implements the DoctrineWorkable interface:

interface DoctrineWorkable {
    public function setEntityManager(EntityManager $manager);

trait EntityManagerTrait {
   protected $manager;

    public function setEntityManager(EntityManager $manager) {
        $this->manager = $manager;
        // Other work with $manager

class TestController implements DoctrineWorkable {
    use EntityManagerTrait;

How to use the setEntityManager method in a service container? To get something like this:

if ($class instanceof DoctrineWorkable) {
    $class->setEntityManager(new EntityManager());

p.s. Sorry for the bad English ))



I think you are overcomplicating things a little bit. The controller is not a service, so it won't be passed as an object (at least on programmer controlled level). This means that you can and should control dependency injection yourself. So, according to the docs, there are three options to point to the Laravel that your controller needs any dependencies:

1. Constructor Injection

If you want to ensure that some controllers always have entity manager available to them, you can create a parent class. But I actually don't see the real value in this, accepts maybe you use a couple of entity managers, and they have to be passed to the different controllers.

2. Method Injection

As not all actions in the controller usually use entity manager, it might be a valid option.

If you read the laravel doctrine docs you can find there another option, that uses facade:

You can use the facade to access the EntityManager methods

Anyway, in my opinion, interfaces should be used to define a contract, and not to define the availability of some internal functionality.

Regarding // Other work with $manager:

You can extend your entity manager on service provider level. There're also several options on how to do this. You can find them in the documentation.