Search code examples
phpsymfonyconfig

Symfony4 bundle creation - impossible to generate a config file


A code demo from this problem is visible on : GitHub and Packagist, please consult v0.0.3.

My problem : I want to generate a config\packages\owner_test.yaml file when I run :

composer require owner/test-bundle:0.0.3

But Composer display an error :

There is no extension able to load the configuration for "owner_test" (in "C:\Users\USER\PROJECT\vendor\owner\test-bundle\DependencyInjection/../Resources/config\owner_test.yaml"). Looked for namespace "owner_test", found "none".

Root key and bundle name is corrects and I have read all documentation finded, but nothing is right :

Thanks for help


Solution

  • Here is a working example: https://github.com/cerad/bundle4

    The bundle source is in the src-owner directory

    What you are missing and perhaps not fully understanding is the bundle's Configuration class:

    namespace Owner\TestBundle\DependencyInjection;
    
    use Symfony\Component\Config\Definition\Builder\TreeBuilder;
    use Symfony\Component\Config\Definition\ConfigurationInterface;
    
    class Configuration implements ConfigurationInterface
    {
        public function getConfigTreeBuilder()
        {
            $treeBuilder = new TreeBuilder('owner_test');
            $treeBuilder->getRootNode()
                ->children()
                    ->booleanNode('isDisplay')->defaultTrue()->end()
                    ->booleanNode('someBoolean')->defaultTrue()->end()
                ->end()
            ;
            return $treeBuilder;
        }
    }
    

    The Configuration class is used to setup default config values for your bundle. These values can be overridden at the application level via a config/packages/owner_test.yaml. Your bundle will not have it's own config yaml file. Things just don't work that way.

    Your extension then becomes:

    namespace Owner\TestBundle\DependencyInjection;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\Extension\Extension;
    
    class OwnerTestExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            // Has what is in config/packages/owner_test.yaml
            dump($configs);
    
            $configuration = new Configuration();
    
            $config = $this->processConfiguration($configuration, $configs);
            dump($config);
    
            // At this point you would use $config to define your parameters or services
    
        }
    }
    

    Study the dump outputs and read the docs until you understand what is happening as the config is processed. Just use "bin/console cache:clear". I added a second config value just to make it a bit easier to understand. You will probably want to add more.

    At this point it up to you to add code to transfer your config values to the ContainerBuilder.