Symfony 服务的可选参数依赖关系
我知道我可以为服务添加可选的服务依赖项。语法是Symfony 服务的可选参数依赖关系,symfony,Symfony,我知道我可以为服务添加可选的服务依赖项。语法是 arguments: [@?my_mailer] 但是如何为服务添加可选的参数依赖项 arguments: [%my_parameter%] 我试过了 arguments: [%?my_parameter%] arguments: [?%my_parameter%] 但是这两种方法都不起作用,sf2中是否实现了此功能?是否尝试为参数设置默认值?像这样: namespace Acme\FooBundle\Services; class Bar
arguments: [@?my_mailer]
但是如何为服务添加可选的参数依赖项
arguments: [%my_parameter%]
我试过了
arguments: [%?my_parameter%]
arguments: [?%my_parameter%]
但是这两种方法都不起作用,sf2中是否实现了此功能?是否尝试为参数设置默认值?像这样:
namespace Acme\FooBundle\Services;
class BarService
{
public function __construct($param = null)
{
// Your login
}
}
不注入任何东西。我认为如果不传递/设置参数,Symfony会抱怨服务依赖性。您希望将参数设置为可选参数,这样就不需要总是在config.yml文件中进行设置。您希望在设置该参数时使用该参数 我的解决方案是:
# src/Acme/HelloBundle/Resources/config/services.yml
parameters:
my_parameter:
services:
my_mailer:
class: "%my_mailer.class%"
arguments: ["%my_parameter%"]
然后
# you-bundle-dir/DependencyInjection/Configuration.php
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('you_bundle_ns');
// This is for wkhtmltopdf configuration
$rootNode
->children()
->scalarNode('my_parameter')->defaultNull()->end()
->end();
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
然后
# you-bundle-dir/DependencyInjection/YourBundleExtension.php
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.xml');
$container->setParameter(
'you_bundle_ns.your_parameter',
isset($$config['you_bundle_ns']['your_parameter'])?$$config['you_bundle_ns']['your_parameter']:null
);
}
通过为“%parameter%”提供默认值,可以使参数成为可选的
如果您有更好的选择,请告诉我。从Symfony 2.4可以使用表达式: 参数:[“@=container.hasParameter('some_param')? 参数('some_param'):'default_value']
更多信息参见可选参数的好处是什么?参数用于在不同环境之间改变配置。您可以在不同的环境中改变配置,但这并没有那么干净。
$$config
输入错误?Symfony将抛出ParameterNotFoundException!此外,还可以使用参数:[“@=parameter('some_param')?parameter('some_param'):'default_value']