PhpRiot
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

Creating an Instance of a Table

Before you use a Table class, create an instance using its constructor. The constructor's argument is an array of options. The most important option to a Table constructor is the database adapter instance, representing a live connection to an RDBMS. There are three ways of specifying the database adapter to a Table class, and these three ways are described below:

Specifying a Database Adapter

The first way to provide a database adapter to a Table class is by passing it as an object of type Zend_Db_Adapter_Abstract in the options array, identified by the key 'db'.

Example 273. Example of constructing a Table using an Adapter object

<?php
$db 
Zend_Db::factory('PDO_MYSQL'$options);

$table = new Bugs(array('db' => $db));

Setting a Default Database Adapter

The second way to provide a database adapter to a Table class is by declaring an object of type Zend_Db_Adapter_Abstract to be a default database adapter for all subsequent instances of Tables in your application. You can do this with the static method Zend_Db_Table_Abstract::setDefaultAdapter(). The argument is an object of type Zend_Db_Adapter_Abstract.

Example 274. Example of constructing a Table using a the Default Adapter

<?php
$db 
Zend_Db::factory('PDO_MYSQL'$options);
Zend_Db_Table_Abstract::setDefaultAdapter($db);

// Later...

$table = new Bugs();

It can be convenient to create the database adapter object in a central place of your application, such as the bootstrap, and then store it as the default adapter. This gives you a means to ensure that the adapter instance is the same throughout your application. However, setting a default adapter is limited to a single adapter instance.

Storing a Database Adapter in the Registry

The third way to provide a database adapter to a Table class is by passing a string in the options array, also identified by the 'db' key. The string is used as a key to the static Zend_Registry instance, where the entry at that key is an object of type Zend_Db_Adapter_Abstract.

Example 275. Example of constructing a Table using a Registry key

<?php
$db 
Zend_Db::factory('PDO_MYSQL'$options);
Zend_Registry::set('my_db'$db);

// Later...

$table = new Bugs(array('db' => 'my_db'));

Like setting the default adapter, this gives you the means to ensure that the same adapter instance is used throughout your application. Using the registry is more flexible, because you can store more than one adapter instance. A given adapter instance is specific to a certain RDBMS brand and database instance. If your application needs access to multiple databases or even multiple database brands, then you need to use multiple adapters.

Zend Framework