Laravel解决闭包的依赖 [英] Laravel resolving dependencies for a closure

查看:84
本文介绍了Laravel解决闭包的依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel能够自动将依赖项注入控制器构造等中. 例如:

Laravel is able to automatically inject dependencies in controller constructs, etc. For example:

class Test {
    public function __construct(Request $request) {}
}

App::make('Test');

控制器的构造函数将接收适当的请求外观.

The controller's constructor will receive the appropriate request facade.

有没有办法用闭包做到这一点?

Is there a way to do this with closures?

例如:

$closure = function(Request $input) {};
App::make($closure); // resolving the closure dependencies

推荐答案

否,不可能,您可以在此处阅读IoC容器代码:

No, it's not possible, you may read through the IoC container code here:

laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php在行466

如您所见,它试图通过反射来解析和解析父类的__constructor方法.

As you see it tries to resolve and parse parents Class's __constructor method through reflections.

我认为实现起来会很有趣,因为很可能通过扩展Container类来支持闭包.

I think that would be interesting to implement, as it's quite possible by extending the Container class to also support closures.

我已经进行了几次测试以确保可行,所以这里是:

I have made a couple of tests to make sure it is possible, so here they are:

    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将引发异常.

Type hinting t5 will throw the exception.

这回答了问题

有没有办法用闭包做到这一点?

Is there a way to do this with closures?

关于如何实现它,我认为您应该对反射和Laravel IoC容器的工作原理有全面的了解.我认为这不会在不久的将来实现,因为Laravel基本上是建立在类上的.您的用例是什么?

As to how implement it, in my opinion you should have perfect knowledge of how reflections and Laravel IoC container work. I think this will not be implemented in near future as Laravel is basically built on classes. What are your use cases?

这篇关于Laravel解决闭包的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆