Config extension
Symfony configuration extension without bundle.
Installation
| composer require symfony/config symfony/dependency-injection
|
How to
Define a configuration tree:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | namespace App\Infra\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class FoobarConfiguration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('foobar');
$root = $treeBuilder->getRootNode();
$root
->children()
->scalarNode('foo')->end()
->end()
;
return $treeBuilder;
}
}
|
Create the extension:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | namespace App\Infrastructure\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class FoobarExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new FoobarConfiguration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('foobar.foo', $config['foo']);
}
}
|
Then register your extension in the kernel:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | namespace App;
use App\Infra\DependencyInjection\FoobarExtension;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
// ...
protected function build(ContainerBuilder $container)
{
$container->registerExtension(new FoobarExtension());
}
}
|
Note: You can register as many extension you want.
And use the configuration:
| # config/packages/foobar.yaml
foobar:
foo: bar
|
You can now use the the parameters foobar.foo
in services.
Last update: December 20, 2024