Laravel是否有能力通过方法引入依赖?
例如,我有一个实现DoctrineWorkable
接口的控制器:
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;
}
如何在服务容器中使用setEntityManager
方法?得到这样的东西:
if ($class instanceof DoctrineWorkable) {
$class->setEntityManager(new EntityManager());
}
P.S。对不起,英语不好))
答案 0 :(得分:0)
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.