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.
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.
require_once('Zend/Registry.php'); require_once('Zend/Db.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.




