Symfony-在捆绑控制器中获取自定义参数

时间:2018-07-18 14:04:02

标签: symfony dependency-injection yaml symfony-3.4

我正在Symfony 3.4.12下运行一个网站,并创建了自己的自定义捆绑包。我在Yaml中有一个自定义配置文件:

    def showselection(self):
        it = self.multiplexerList.currentItem()
        widget = self.multiplexerList.itemWidget(it)
        combo = widget.waveselect
        print(combo.currentText())

...

class MultiplexerListItem(QWidget):
    def __init__(self, main_plot, i,  parent = None):
        super().__init__(parent)
        grid = QGridLayout()
        grid.addWidget(QLabel(str(i + 1)), 0, 0)
        self.waveselect = QComboBox()
        self.waveselect.addItems(["A", "B"])
        self.waveselect.activated[str].connect(main_plot.updateplot)
        grid.addWidget(self.waveselect, 0, 1)
        self.setLayout(grid)

...并以这种方式启动:

# src/CompanyBundle//Resources/config/config.yml

company_bundle:
    phone_number

我想在我的控制器文件中检索我的自定义参数,什么是最好的方法?我尝试过这种方法,但没有成功:

<?php

# src/CompanyBundle/DependencyInjection/CompanyExtension.php 

namespace CompanyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;


class CompanyExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('config.yml');
    }
}

?>

谢谢。

1 个答案:

答案 0 :(得分:1)

您必须定义自己的DependencyInjection/Configuration.phphttp://symfony.com/doc/3.4/bundles/configuration.html#processing-the-configs-array

喜欢:

public function getConfigTreeBuilder()
{
    $treeBuilder = new TreeBuilder();
    $rootNode = $treeBuilder->root('company_bundle');
    $rootNode
        ->children()
            ->scalarNode('phone_number')
            ->end()
        ->end()
    ;
}

然后将其处理到您的DependencyInjection/...Extension.php文件中。如果要将此选项作为参数,则必须这样做:

public function load(array $configs, ContainerBuilder $container) 
{
     // Some default code
    $container->setParameter('company_bundle.phone_number', $config['phone_number']);
}

然后您可以像在控制器中一样在控制器中获取此参数。