Laravel 没有工厂风格的服务容器解析器吗?
Does Laravel not have a factory style service container resolver?
工厂服务的概念在Laravel中存在吗?我想创建一个允许我传递一些额外配置参数的服务提供者。
我习惯了 Silex,在那里我可以使用 Pimple factory
方法:https://github.com/silexphp/Pimple#defining-factory-services
许多其他框架(如 Angular2)也具有此功能,但我在 Laravel 文档中没有看到任何内容 -- 他们的 IoC 容器中不存在此功能吗?
我不知道 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 ] );
工厂服务的概念在Laravel中存在吗?我想创建一个允许我传递一些额外配置参数的服务提供者。
我习惯了 Silex,在那里我可以使用 Pimple factory
方法:https://github.com/silexphp/Pimple#defining-factory-services
许多其他框架(如 Angular2)也具有此功能,但我在 Laravel 文档中没有看到任何内容 -- 他们的 IoC 容器中不存在此功能吗?
我不知道 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 ] );