Laravel 能够自动在控制器构造等中注入依赖项。
例如:
class Test {
public function __construct(Request $request) {}
}
App::make('Test');
控制器的构造函数将接收适当的请求外观。
有没有办法用闭包来做到这一点?
例如:
$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 将抛出异常。
这回答了问题
有没有办法用闭包来做到这一点?
至于如何实现它,我认为你应该完全了解反射和 Laravel IoC 容器的工作原理。我认为这不会在不久的将来实现,因为 Laravel 基本上是基于类构建的。您的用例是什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)