Php Symfony 2-命令容器的配置
我在app/config.yml示例中定义了:Php Symfony 2-命令容器的配置,php,symfony,command,Php,Symfony,Command,我在app/config.yml示例中定义了: module_my_module key: value1 key2: value2 以及一个带有DependecyInjection Configuration.php的捆绑包: <?php namespace Modules\Bundle\MyModuleBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuild
module_my_module
key: value1
key2: value2
以及一个带有DependecyInjection Configuration.php的捆绑包:
<?php
namespace Modules\Bundle\MyModuleBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('module_configuration');
$rootNode->children()
->scalarNode('key')->defaultValue('')->end()
->scalarNode('key2')->defaultValue('')->end()
->end()
;
return $treeBuilder;
}
}
Config.yml:
module_configuration
key: val
必须将参数注入
扩展
捆绑类定义中的容器中
在您的情况下,您必须具有类似于:
<?php
namespace Modules\Bundle\MyModuleBundle\DependencyInjection;
class MyModuleExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('...');
$container->setParameter('my_first_key', $config['key']);
$container->setParameter('my_second_key', $config['key2']);
}
}
希望此帮助在
containerWareCommand
中,您可以通过$this->getContainer()->getParameter(“param_name”)
<?php
namespace Modules\Bundle\MyModuleBundle\DependencyInjection;
class MyModuleExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('...');
$container->setParameter('my_first_key', $config['key']);
$container->setParameter('my_second_key', $config['key2']);
}
}
class MyCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->getContainer()->getParameter("my_first_key");
}
}