>>Friday, February 12, 2010<<
When I am working on Zend Framework projects I usually find that I am referencing .ini files a lot within my code, which usually means typing the following line many times:
<?php
$oConfig = new Zend_Config_Ini("../application/configs/config.ini");
?>
Although it is simple enough to remember, it does get tedious after a while and I always wondered what the execution time of the code was like calling the same config file multiple times on each load (i.e. in different classes).
A simple way to get around this is to use the Zend_Registry() class and store the config file in the registry on the first load, but unless you load all of the config files initially you end up with lines like:
<?php
if (!Zend_Registry::isRegistered("config.ini"))
Zend_Registry::set("config.ini", Zend_Config_Ini("../application/config/config.ini"));
$oConfig = Zend_Registry::get("config.ini");
?>
So I decided to find a solution that was quick and simple. The interaction we desire looks like this:
<?php
$oConfig = Val_Config::get("config.ini");
?>
See how much simpler that is to use and remember?
So, how do we do it?
<?php
/****
* Val_Config
*
* Simple class for loading Zend_Config_Ini files quickly
*
* @author Stephen "Valorin" Rees
* @version 1.0-thoughts
* @url http://valorin.net/thoughts/view/id/7#Zend_Framework_Simple_Configuration_Class
*/
class Val_Config
{
/**
* @var String Array to store our cached .ini files in
*/
protected static $aCache;
/**
* @var String Default path for the config files
*/
protected static $sConfigPath = "../application/configs/";
/**
* Override the default config file path on-the-fly
*
* @param String $sPath Default path, relative to index.php
*/
public static function setConfig($sPath)
{
self::$sConfigPath = $sPath;
}
/**
* Get config.ini file contents
*
* @param String $sType The filename of the config file we want to retrieve
* @param String $sName (optional) the specific section of the config file to return
* @return Zend_Config_Ini
*/
public static function get($sType, $sName = null)
{
/**
* Generate the key to store the data under
*/
$sKey = "{$sType}::{$sName}";
/**
* Check if we have the data in our cache array
* if we don't have any data, load it and store it in the cache
*/
if (!isset(self::$aCache[$sKey]))
self::$aCache[$sKey] = new Zend_Config_Ini(self::$sConfigPath.$sType, $sName);
/**
* Return the cache file contents to the user
*/
return self::$aCache[$sKey];
}
}
?>
And there we have a very simple way of loading configuration files. I have expanded this config class to also load and save settings in a database, but that is for another post. I hope you find this useful, and feel free to use it however you'd like.
Note: there is no error checking in this example, so if you throw it dodgy data... it is your own fault if it breaks :)
Tags: scripts, val_config, zend_config_ini, zf
No comments have been left yet...