php - Laravel 解决闭包的依赖关系

标签 php dependency-injection laravel

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/

相关文章:

php - 查询中 WHERE 约束的顺序

php - CodeIgniter 中的字段级 ACL

.net - 将 InterceptionBehaviour 添加到 IoC 容器中注册的所有内容

c# - Presenter 的依赖注入(inject)

mysql - 如何从 Laravel 中的一张 "user"表中建立父子关系

php - 解析简单明确定义的字符串的最有效方法?

c# - DryIoC - 在解析时指定一些构造函数参数

laravel - Laravel应用程序无法在本地写入文件,引发使用docker拒绝的权限

Laravel 对不正确的 url 返回真实的验证

php - IE : Unexpected call to method or property access 中的奇怪 jQuery 错误