【问题标题】:Does Laravel not have a factory style service container resolver?Laravel 没有工厂风格的服务容器解析器吗?
【发布时间】:2016-11-06 21:39:23
【问题描述】:

Laravel 中是否存在工厂服务的概念?我想创建一个允许我传递一些额外配置参数的服务提供者。

我习惯了 Silex,我可以使用 Pimple factory 方法:https://github.com/silexphp/Pimple#defining-factory-services

像 Angular2 这样的许多其他框架也有这个功能,但我在 Laravel 文档中没有看到任何内容——他们的 IoC 容器中不存在这个功能吗?

【问题讨论】:

    标签: php laravel dependency-injection laravel-5 ioc-container


    【解决方案1】:

    我不知道 Silex,但在 Laravel 中,您可以通过这种方式从带有附加参数的 ioc 容器创建服务:

     App::bind( YourService::class, function($app)
    {
        //create YourService passing Dependency from ioc container
        return new yourService( $app->make( Dependency::class ) );
    });
    

    此外,如果您需要从调用代码动态传递这些参数,您可以让 ioc 容器接收它们:

    //bind the service accepting extra parameters
    App::bind( YourService::class, function($app, array $parameters)
    {
        //create YourService passing a parameter got from the calling code  
        return new YourService( $parameters[0] );
    } );
    

    然后将参数传递给ioc容器:

    //create the instance passing $myParameter 
    $instance = App::make( YourService::class,  [ $myParameter ]  );
    

    【讨论】:

    • 明白了,谢谢 - 它没有在文档中指定您可以将附加参数传递给绑定闭包,这很有帮助
    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2018-06-23
    • 2016-06-06
    • 1970-01-01
    • 2019-04-24
    • 2023-03-10
    相关资源
    最近更新 更多