Dependency Injection Through A Setter
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 ))
Answer
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.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?