0

I'm running a website under Symfony 3.4.12 and I created my own custom bundle. I have a custom config file in Yaml :

# src/CompanyBundle//Resources/config/config.yml

company_bundle:
    phone_number

... and it is launched this way :

<?php

# src/CompanyBundle/DependencyInjection/CompanyExtension.php 

namespace CompanyBundle\DependencyInjection;

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


class CompanyExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('config.yml');
    }
}

?>

I would like to retrieve my custom parameters in my controller file, what is the best way to do it ? I tried this way, with no success :

$this->getParameter('company_bundle.phone_number')

Thanks.

1
  • 2
    Read up a bit more on custom configuration. You will need a configuration tree and then use $container->setParameter to create the parameters. Or just define your phone_number as a parameter to start with. Just like the answer below says though I did beat his post by about 4 seconds. Commented Jul 18, 2018 at 14:33

1 Answer 1

1

You have to define your own DependencyInjection/Configuration.php: http://symfony.com/doc/3.4/bundles/configuration.html#processing-the-configs-array

Like that:

public function getConfigTreeBuilder()
{
    $treeBuilder = new TreeBuilder();
    $rootNode = $treeBuilder->root('company_bundle');
    $rootNode
        ->children()
            ->scalarNode('phone_number')
            ->end()
        ->end()
    ;
}

And then process it into your DependencyInjection/...Extension.php file. If you want to make this option as parameter you have to do it like that:

public function load(array $configs, ContainerBuilder $container) 
{
     // Some default code
    $container->setParameter('company_bundle.phone_number', $config['phone_number']);
}

And then you can get this parameter in your controller like you do.

Sign up to request clarification or add additional context in comments.

2 Comments

It's a little bit too compicated in order to do what I get in my mind. Furthermore, if I have to set every params one by one, it's useless. The idea was to add/edit/remove vars in a yaml file without editing any php file. Many thanks anyway.
@Paolito75 I suppose you can do it in your config.yml inside parameters section. But I'm not sure that this will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.