Laravel 能够自动在 Controller 构造等中注入(inject)依赖项。 例如:
class Test {
public function __construct(Request $request) {}
}
App::make('Test');
Controller 的构造函数将接收适当的请求外观。
有没有办法用闭包来做到这一点?
例如:
$closure = function(Request $input) {};
App::make($closure); // resolving the closure dependencies
最佳答案
不,这是不可能的,您可以在此处阅读 IoC 容器代码:
laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php
上线 466
如您所见,它尝试通过反射来解析和解析父类的 __constructor
方法。
我认为实现起来会很有趣,因为通过扩展 Container
类来支持闭包是很有可能的。
我做了一些测试以确保这是可能的,所以它们是:
class t4 {
public $x = "inject me";
}
interface t5 {}
$t3 = function(t4 $test) {
return print($test);
};
$r = new ReflectionFunction($t3);
$params = $r->getParameters();
$injection = $params[0]->getClass();
if (!$injection->isInstantiable()) {
throw new Exception('Provided type hint is not instantiable');
}
$typehinted = $injection->newInstance();
print($typehinted->x); // prints "inject me"
类型提示 t5 将抛出异常。
这回答了问题
Is there a way to do this with closures?
至于如何实现,我认为你应该充分了解反射和 Laravel IoC 容器的工作原理。我认为这不会在不久的将来实现,因为 Laravel 基本上是基于类构建的。您的用例是什么?
关于php - Laravel 解决闭包的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21779805/