Creating custom config handlers
When writing plugins, you often want to do it the symfony way, by putting configuration stuff in YAML files to allow the final user to override your default values in a harmless way.
To do this, the correct way is to create a config handler, extending
sfConfigHandler, or its child class sfYamlConfigHandler.
Here is a simple one, just dumping YAML data found in your config file into
an sfConfig::get()-able PHP dataset.
<?php
class myStupidConfigHandler extends sfYamlConfigHandler
{
public function execute($configFiles)
{
// retrieve yaml data
$config = $this->parseYamls($configFiles);
$code = sprintf("<?php\n" .
"// auto-generated by myStupidConfigHandler\n" .
"// date: %s\n" .
"sfConfig::set('my_stupid_config_entry', %s);",
date('Y-m-d H:i:s'), var_export($config, 1));
return $code;
}
}
We can enhance it, taking care of symfony environments.
<?php
class myStupidConfigHandler extends sfYamlConfigHandler
{
public function execute($configFiles)
{
// retrieve yaml data
$config = $this->parseYamls($configFiles);
// get current environment
$environment = sfConfig::get('sf_environment');
// merge default and environment specific config
$config = sfToolkit::arrayDeepMerge(isset($config['all'])?$config['all']:array(), isset($config[$environment])?$config[$environment]:array());
$code = sprintf("<?php\n" .
"// auto-generated by myStupidConfigHandler\n" .
"// date: %s\n" .
"sfConfig::set('my_stupid_config_entry', %s);",
date('Y-m-d H:i:s'), var_export($config, 1));
return $code;
}
}
Next step will be to tell symfony which configuration file patterns should
be loaded using our class. To do this, add the following entry to
config/config_handlers.yml (whether in your app, plugin or module, depending on
the scope of your config handler)
config/stupid.yml:
class: myStupidConfigHandler
Once this is done, the very little remaining last step is to make sure you include the compiled yml.php file with the following magic command, that will rebuild it when unexistant or outdated:
<?php
require_once(sfConfigCache::getInstance()->checkConfig('config/stupid.yml'));
/* ... */
$stupid_config = sfConfig::get('my_stupid_config_entry');
easy one :-)