将Symfony2服务配置移动到捆绑包

时间:2011-11-29 21:14:12

标签: symfony

我的config.yml

中有以下内容
services:
    my.user_provider:
        class: Acme\MySecurityBundle\Security\UserProvider

但是想把它移到我的MySecurityBundle/Resources/config中的config.yml,但Symfony2告诉我,当我移动它时该服务不存在。

如何从那里获取config.yml文件?

3 个答案:

答案 0 :(得分:40)

src/Acme/MySecurityBundle/DependencyInjection/MySecurityExtension.php

<?php
namespace Acme\MySecurityBundle\DependencyInjection;

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

class MySecurityExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

src/Acme/MySecurityBundle/Resources/config/services.yml

services:
    my_security.user_provider:
        class: Acme\MySecurityBundle\Security\UserProvider

答案 1 :(得分:21)

我通过在app/config.yml中引用它作为导入来完成此操作:

imports:
    - { resource: "@MySecurityBundle/Resources/config/services.yml" }

答案 2 :(得分:16)

您需要在该捆绑中创建一个名为“扩展”的类,它告诉Symfony在加载捆绑包时要做什么。命名约定有点奇怪。对于Acme \ MySecurityBundle,该类将命名为AcmeMySecurityExtension。它位于{bundlepath} / DependencyInjection。

以下是我的一个示例(我正在加载Resources / config / services.xml):

<?php

namespace Acme\MySecurityBundle\DependencyInjection;

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

/**
 * This class is automatically discovered by the kernel and load() is called at startup.
 * It gives us a chance to read config/services.xml and make things defined there available for use.
 * For more information, see http://symfony.com/doc/2.0/cookbook/bundles/extension.html
 */
class AcmeMySecurityExtension extends Extension
{
    /**
     * Called by the kernel at load-time.
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        /*@var XmlFileLoader*/
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.xml');
    }
}