Symfony 2 — настройка для командного контейнера

Я определил в примере 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 class:

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

Решение

Вы должны ввести свои параметры в Контейнер в Extension Определение класса связки.

В вашем случае у вас должно быть что-то похожее на:

<?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");
}

}

Надеюсь это поможет

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector