Magento Themes and Magento Extensions

Symfony2 custom config parameters

Share

Sometimes we need to add some static configuration options inside our project that will be accessible from whole project scope.

For example, I wanted to define some custom DateTime format that I will use in more then one bundles to format my output to mobile device.

I didn’t want to write format string again and again in code, because after 2 years as my project expanding, I maybe will not be able to quickly find where I defined that output format to reuse it.

Then I decided to try to put configuration option inside config.yml file and when I change value there, it will be changed elsewhere in the project so I dont need to search and replace this values one by one.

This is my custom parameters:

#config.yml
surgeworks_core:
api_dateformat: "Y-m-d\TH:i:s\Z"
api_item_cache_lifetime: 3600
api_item_cache_enabled: false

Ok. I defined needed parameters inside config file, but I have to find proper way to access them inside application.

Now, let’s modify Configuration.php file a little bit …

//Surgeworks/CoreBundle/DependencyInjection/Configuration.php
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('surgeworks_core')->children()
->variableNode('api_dateformat')
->defaultValue("Y-m-d\TH:i:s\Z")
->end()
->variableNode('api_item_cache_lifetime')
->defaultValue("86400")->end()
->booleanNode('api_item_cache_enabled')->defaultTrue()->end();
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}

Of course, we need some more coding inside ‘SurgeworksCoreExtension’:

//Surgeworks/CoreBundle/DependencyInjection/SurgeworksCoreExtension.php
class SurgeworksCoreExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('api_dateformat', $config['api_dateformat']);
$container->setParameter('api_item_cache_lifetime', $config['api_item_cache_lifetime']);
$container->setParameter('api_item_cache_enabled', $config['api_item_cache_enabled']);
$loader = new Loader\XmlFileLoader
($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}

I just have to use my new config values inside controller like this:

//...
$this->container->getParameter('api_dateformat');

This is all for today. Pleasant coding!

Leave a Reply

You must be logged in to post a comment.