如何在Symfony2控制器中访问语义配置?

6

我正在遵循Symfony 2官方手册中的“如何为Bundle公开语义化配置”的内容。

我有我的configuration.php文件。

namespace w9\UserBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('w9_user');

        $rootNode
            ->children()
                ->scalarNode('logintext')->defaultValue('Zareejstruj się')->end()
            ->end()
        ;        

        return $treeBuilder;
    }
}

并且 w9UserExtension.php:

namespace w9\UserBundle\DependencyInjection;

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

class w9UserExtension 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('services.yml');
    }
}

可能听起来很傻,但我无法找到在控制器中访问logintext参数的方法?

$logintext = $this->container->getParameter("w9_user.logintext");

不起作用。

我做错了什么?

2个回答

11

w9UserExtension.php中,在processConfiguration行后添加以下内容:

$container->setParameter('w9_user.logintext', $config['logintext']);

3
如果我有一堆配置参数,我如何一次性设置它们? - acme
@acme 我也想这样做。请看下面我的回答。 - LaGoutte

0

我想无差别地将所有我的配置值添加到参数中,如@acme,写数十个setParameter行还不够懒。

因此,我创建了一个setParameters方法以添加到Extension类。

/**
 * Set all leaf values of the $config array as parameters in the $container.
 *
 * For example, a config such as this for the alias w9_user :
 *
 * w9_user:
 *   logintext: "hello"
 *   cache:
 *      enabled: true
 *   things:
 *      - first
 *      - second
 *
 * would yield the following :
 *
 * getParameter('w9_user.logintext') == "hello"
 * getParameter('w9_user.cache') ---> InvalidArgumentException
 * getParameter('w9_user.cache.enabled') == true
 * getParameter('w9_user.things') == array('first', 'second')
 *
 * It will resolve `%` variables like it normally would.
 * This is simply a convenience method to add the whole array.
 *
 * @param array $config
 * @param ContainerBuilder $container
 * @param string $namespace The parameter prefix, the alias by default.
 *                          Don't use this, it's for recursion.
 */
protected function setParameters(array $config, ContainerBuilder $container,
                                 $namespace = null)
{
    $namespace = (null === $namespace) ? $this->getAlias() : $namespace;

    // Is the config array associative or empty ?
    if (array_keys($config) !== range(0, count($config) - 1)) {
        foreach ($config as $k => $v) {
            $current = $namespace . '.' . $k;
            if (is_array($v)) {
                // Another array, let's use recursion
                $this->setParameters($v, $container, $current);
            } else {
                // It's a leaf, let's add it.
                $container->setParameter($current, $v);
            }
        }
    } else {
        // It is a sequential array, let's consider it as a leaf.
        $container->setParameter($namespace, $config);
    }
}

你可以像这样使用它:

class w9UserExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        // Add them ALL as container parameters
        $this->setParameters($config, $container);

        // ...
    }
}

警告

如果您没有广泛记录和/或需要这样的行为,那么这可能是不良做法,因为如果您忘记它,可以公开敏感配置信息,并通过公开无用配置来降低性能。

此外,它会防止您在将配置变量添加到容器的参数包中之前进行广泛的清理。

如果您使用此功能,则应该使用parameters:而不是语义配置,除非您知道自己在做什么。

请自行承担风险。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接