05/06/2015 - SYMFONY
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.
# User file uploads
football_frontend:
upload:
image: "%kernel.root_dir%/upload/image/"
document: "%kernel.root_dir%/upload/document/"
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;
}
}
# 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');
}
}
$data = $this->container->getParameter('upload');
echo '<pre>';
print_r($data);
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%
Array
(
[image] => /Library/WebServer/Documents/sport/app/upload/image/
[document] => /Library/WebServer/Documents/sport/app/upload/document/
)