Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

First of all, if you want to define system wide variables then I would suggest you to use parameters.yml file. If you use config.yml file for same reason, you'll add a bit of complexity to your application configurations but it's up to you. Example below shows us how to do it with config.yml and access data in controllers or services.


Config YML


# User file uploads
football_frontend:
upload:
image: "%kernel.root_dir%/upload/image/"
document: "%kernel.root_dir%/upload/document/"

Configuration


Click here for more information about configurations.


# sport/src/Football/FrontendBundle/DependencyInjection/Configuration.php

namespace Football\FrontendBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('football_frontend');

$rootNode
->children()
->arrayNode('upload')
->children()
->scalarNode('image')
->cannotBeEmpty()
->end()
->scalarNode('document')
->cannotBeEmpty()
->end()
->end()
->end()
->end();

return $treeBuilder;
}
}

Extension registration


# sport/src/Football/FrontendBundle/DependencyInjection/FootballFrontendExtension.php

namespace Football\FrontendBundle\DependencyInjection;

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

class FootballFrontendExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$container->setParameter('upload', $config['upload']);

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}

Option 1: Direct access in controller


$data = $this->container->getParameter('upload');
echo '<pre>';
print_r($data);

Option 2: Injecting as a parameter with services YML


You can handle upload variable in __construct() method of your service, controller, factory etc.


# sport/src/Football/FrontendBundle/Resources/config/controllers.yml
services:
football_frontend.service.upload:
class: Football\FrontendBundle\Service\UploadService
arguments:
- %upload%

Result


Array
(
[image] => /Library/WebServer/Documents/sport/app/upload/image/
[document] => /Library/WebServer/Documents/sport/app/upload/document/
)