Move Symfony2 service config to bundle

后端 未结 3 910
有刺的猬
有刺的猬 2021-01-31 04:59

I have the following in my config.yml

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

but would l

相关标签:
3条回答
  • 2021-01-31 05:27

    I accomplished this by referencing it as an import in app/config.yml:

    imports:
        - { resource: "@MySecurityBundle/Resources/config/services.yml" }
    
    0 讨论(0)
  • 2021-01-31 05:27

    You need to create a class in that bundle called an 'extension' that tells Symfony what to do when loading the bundle. The naming convention is a little weird. For Acme\MySecurityBundle, the class will be named AcmeMySecurityExtension. It lives in {bundlepath}/DependencyInjection.

    Here is an example of one of mine (I am loading 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');
        }
    }
    
    0 讨论(0)
  • 2021-01-31 05:29

    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
    
    0 讨论(0)
提交回复
热议问题