Zend_Config | Zend_Config Programmer's Reference Guide | Theory of Operation

# Introduction

Zend_Config is designed to simplify the access to, and the use of, configuration data within applications. It provides a nested object property based user interface for accessing this configuration data within application code. The configuration data may come from a variety of media supporting hierarchical data storage. Currently Zend_Config provides adapters for configuration data that are stored in text files with Zend_Config_Ini and Zend_Config_Xml.

Example #1 Using Zend_Config

Normally it is expected that users would use one of the adapter classes such as Zend_Config_Ini or Zend_Config_Xml, but if configuration data are available in a PHP array, one may simply pass the data to the Zend_Config constructor in order to utilize a simple object-oriented interface:

1. // Given an array of configuration data
2. $configArray = array(
3. 'webhost' => 'www.example.com',
4. 'database' => array(
5. 'adapter' => 'pdo_mysql',
6. 'params' => array(
7. 'host' => 'db.example.com',
8. 'username' => 'dbuser',
9. 'password' => 'secret',
10. 'dbname' => 'mydatabase'
11. )
12. )
13. );
15. // Create the object-oriented wrapper upon the configuration data
16. $config = new Zend_Config($configArray);
18. // Print a configuration datum (results in 'www.example.com')
19. echo $config->webhost;
21. // Use the configuration data to connect to the database
22. $db = Zend_Db::factory($config->database->adapter,
23. $config->database->params->toArray());
25. // Alternative usage: simply pass the Zend_Config object.
26. // The Zend_Db factory knows how to interpret it.
27. $db = Zend_Db::factory($config->database);

As illustrated in the example above, Zend_Config provides nested object property syntax to access configuration data passed to its constructor.

Along with the object oriented access to the data values, Zend_Config also has get() which will return the supplied default value if the data element doesn't exist. For example:

1. $host = $config->database->get('host', 'localhost');

Example #2 Using Zend_Config with a PHP Configuration File

It is often desirable to use a pure PHP-based configuration file. The following code illustrates how easily this can be accomplished:

1. // config.php
2. return array(
3. 'webhost' => 'www.example.com',
4. 'database' => array(
5. 'adapter' => 'pdo_mysql',
6. 'params' => array(
7. 'host' => 'db.example.com',
8. 'username' => 'dbuser',
9. 'password' => 'secret',
10. 'dbname' => 'mydatabase'
11. )
12. )
13. );

1. // Configuration consumption
2. $config = new Zend_Config(require 'config.php');
4. // Print a configuration datum (results in 'www.example.com')
5. echo $config->webhost;

Zend_Config | Zend_Config Programmer's Reference Guide | Theory of Operation