Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Registry

Sample Usage of Zend_Registry

At this stage it may not be entirely clear why Zend_Registry is of use. The prime example of its usefulness is how you access global objects from anywhere in your application.

For instance, your application may use a database. Typically in this scenario you will create your database connection at the start of the request, then continually access the object to perform SQL queries as required.

Note: In the example of this page we use Zend_Db. Zend_Db does not actually make a connection to the database until you perform a query or call the getConnection() method on the adapter.

You will often have many different classes which then require this database connection. It can be quite a pain and somewhat messy to pass the connection between all your classes and functions, so accessing the database connection through the registry becomes extremely useful.

In listing 5 we will define a class that saves new users to a database. We will then access this class to save the user.

Listing 5 Using the registry to store database connection (listing-5.php)
    Zend_Registry::set('db', Zend_Db::factory());
    class User
        public static function create($name)
            $values = array(
                'name' => $name
            $db = Zend_Registry::get('db');
            $db->insert('users', $values);
    User::create('Quentin Zervaas');

In this example, we can simply cal the User::create() method and that method will retrieve the database connection from the registry as required.

In This Article