Monday, July 6, 2009

Zend Framework: Zend_Config examples

Zend_Config is used to simply access to, and use of configuration data in Zend Framework application.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => localhost',
'username' => 'user_name',
'password' => 'user_password',
'dbname' => 'database_name'

You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
$config = new Zend_Config($configArray);

Now, if you want to make database configuration, simply write
$db= Zend_Db::factory($config->database);

To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.

database.adapter = pdo_mysql = localhost
database.params.username = user_name
database.params.password = user_password
database.params.dbname = database_name

After defining ini file, simply write
$config = new Zend_Config_Ini(‘path/to/ini/config.ini’,’ development’);

in your application.

The database configuration is same as we done earlier.
$db = Zend_Config::factory($config->database);

Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
<?xml version="1.0"?>
< development >
</ development >

Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
$db = Zend_Db::factory($config->database);

That's it. cheers.


  1. Thanks too. It helped me! :)

  2. Is it possible to take data from an xml file?????????

    if possible please give me detailed explanation on it,....

    Thank you

  3. fatal error: Call to undefined method Zend_Config::factory() while executing query operations

  4. after incluing config.ini i.e., $config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);

    we have to use $db = Zend_Db::factory($config->database); instead of $db = Zend_Config::factory($config->database);