Symfony 2 - 命令容器的配置

时间:2015-01-15 10:50:57

标签: 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\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.Bundle / Command类:

namespace Modules\Bundle\MyBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

//use \Modules\Bundle\NodeSocketBundle\DependencyInjection as DependencyInjection;

class MyCommand extends ContainerAwareCommand
{

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    $this->getParams("key.val"); // GEt a key from config.yml
    }

}

Config.yml:

module_configuration
     key:  val

1 个答案:

答案 0 :(得分:1)

您必须在Extension Bundle Class定义中注入您的params。

在你的情况下,你必须有类似的东西:

<?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']);

    }
}

然后,您可以在Command课程中访问该值:

class MyCommand extends ContainerAwareCommand
{

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    $this->getContainer()->getParameter("my_first_key");
    }

}

希望这个帮助