Search code examples
phpsymfonysymfony4

How to load a custom config file in a Bundleless application with Treebuilder?


I'm trying to import a custom config file called test.yaml.

I put the test.yaml in the config/packages/local folder and in config/packages folder.

The test.yaml file looks like this:

# config/packages/test.yaml
test1: 'hello'

When I compile the application I get this error: "There is no extension able to load the configuration for "test1"

Now You're gonna to tell me that i need to create and extension and blabla. But I cannot figure out. Is there a way to create an extension without creating a Bundle. I cannot find any example on the documentation that talks about Extension outside a Bundle scope. I mean I want to create it in the src folder ?

A related question is: If I setup a TreeBuilder like in this example: https://symfony.com/doc/current/components/config/definition.html

is it possible to avoid to create an Extension ?

The Symfony version is 5.1.


Solution

  • Seems like I saw a similar question a few months ago but can't find it. The src/Kernel class acts as a AppBundle class and allows you to do things like register extensions.

    # src/Kernel.php
    class Kernel extends BaseKernel
    {
        use MicroKernelTrait;
    
        protected function prepareContainer(ContainerBuilder $container)
        {
            $container->registerExtension(new TestExtension());
            parent::prepareContainer($container);
        }
    ...
    # src/TestExtension.php
    class TestExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            // TODO: Implement load() method.
            dump($configs);
        }
    }
    

    As far as processing a tree builder without an extension, I don't know if that is possible. The config stuff is already complicated enough so I would not go there myself.

    Bit off-topic, I could not find an actual documented case of using prepareContainer in Kernel. The source code makes it clear that the approach shown above will work.

    Most of the time app specific configurations are just done in the config directory. The main point of the bundle configuration system is to allow the app to override default bundle configurations. I'm not really seeing the point of an app level extension. What would override it? Maybe some sort of sophisticated database driven tree builder? Seems unlikely.

    This could be a case of just because you can do something does not mean you should.