有时我们需要在config.yml中为自己的bundle配置一些信息,运用到程序中,那么这需要几个步骤:
1. 新建一个测试bundle吧
输入命令:php app/console generate:bundle 来创建 Tese/BlogsBundle
2. 查看Configuration
我们打开TeseBlogsBundle下的 src\Tese\BlogsBundle\DependencyInjection\Configuration.php文件,并添加代码
1 2 3 4 5 |
$rootNode ->children() ->scalarNode('vlue')->defaultValue('defaultvalue')->end() ->end() ; |
到Configuration.php文件中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?php namespace Tese\BlogsBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('tese_blogs'); //此处添加配置 $rootNode ->children() ->scalarNode('vlue')->defaultValue('defaultvalue')->end() ->end() ; // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } } |
这里面的代码主要实现config.yml中的配置并验证它。
这段代码的主要是为我们做了添加子节点vlue,并给他赋予默认值 defaultvalue。
3. 在config.yml中配置参数
好了打开app\config\config.yml吧,在尾部添加代码
1 2 |
tese_blogs: vlue: "succeed" |
4. 将配置设置成容器参数
打开src\Tese\BlogsBundle\DependencyInjection\TeseBlogsExtension.php文件,加入代码
1 |
$container->setParameter('tese_blogs', $config); |
TeseBlogsExtension.php文件如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php namespace Tese\BlogsBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class TeseBlogsExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $container->setParameter('tese_blogs', $config); } } |
5. 好了可以使用了
打开DefalutController,加入代码
1 2 |
$value= $this->container->getParameter('tese_blogs'); die($value['vlue']); |
好了,喝杯啤酒庆祝一下吧!