Zend Framework

Archive for November 7th, 2008

Zend Framework Zend_Config with examples

Posted by Faheem Abbas on November 7, 2008

Zend_Config is used to simplify access to and user of configuration data within application.
Zend_Config can read configuration data from array, ini file and xml files. It uses Zend_Config_Ini to read configuration data form ini files and Zend_Config_Xml adapter to read configuration data form xml files.
Example 1:

To read configuration data form array, see the following code.
First we will define configuration array.

$configData=array(
‘database’ => array(
‘adapter’ => ‘Pdo_Mysql’,
‘params’ => array(
‘host’ => ‘localhost’,
‘username’ => ‘root’,
‘password’ => ‘’,
‘dbname’ => ‘database_name’
)
)
);

The above array contain configuration data for database connection. You can place different configuration data in the above array.
Next
Define configuration object and give the above array as argument to Zend_Config constructor.
The code is

$config=new Zend_Config($configData);

Zend will do the rest of the things for you.
You can then pass this config object to Zend_Db for connecting to the database.
The code may be

Zend_Db::factory($config->database);

Example 2:
Reading configuration data form ini file.
In order to use ini file for your configuration, create config.ini file in your directory structure and add following code to this file.

[development]
database.adapter = Pdo_Mysql
database.param.host = localhost
database.param.username = root
database.param.password =
database.param.dbname = database_name

Now in your bootsrap file

$config= new Zend_Config_Ini(‘path/to/config.ini’,’development’);

And that’s it your configuration with ini file.
Example 3:
Reading configuration data from xml file
In order to read configuration data from the xml file, create config.xml file in your application with the following code
xml_structure

And now in bootstrap file

$config= new Zend_Config_Xml(‘path/to/config.xml’,’development’);

And if you want to make Zend_Db configuration then add
$db = Zend_Db::factory($config->database);
That’s it, enjoy.

Posted in Zend Framework | 2 Comments »