Specifying the Database Adapter to Use with the Zend Framework Db_NoRecordExists and Db_RecordExists Validators

Written by James Mansson on June 27, 2013 Categories: Databases, Zend Framework 1

In a previous post, I looked at using the Db_NoRecordExists and Db_RecordExists validators provided by the Zend Framework. As an addendum to that post, I would like to add a note on how to use these validators in a situation where the application works with multiple databases.

I have already looked at Zend Framework support for multiple database connections in this post. If we use the technique described there, we will be able to create a class ultimately derived from Zend_Db_Table_Abstract that is linked to the correct database adapter. We can then use an instance of that class to set up the validator.

To return to the example used in the original post, there we performed the validation against the field serial_number in the machine table. To create the validator, we used the following code:

$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' => 'machine',
        'field' => 'serial_number'
    )
);

This works fine in a application where there is one database, with a default database adapter configured. However, what about an application with multiple databases?

In the latter scenario, we could create a class for the table:

class Application_Model_DbTable_Machine
  extends Application_Model_DbTable_Abstract
{
    protected $_schema = 'mydb1';
    protected $_name = 'machine';
}

For the implementation of the class Application_Model_DbTable_Abstract, which is itself derived from Zend_Db_Table_Abstract, see the multi-database post.

When creating the validator, we would then add a couple of lines to retrieve the appropriate database adapter using this class:

$dbTableMachine = new Application_Model_DbTable_Machine();
$dbAdapter = $dbTableMachine->getAdapter();
$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'adapter' => $dbAdapter,
        'table' => 'machine',
        'field' => 'serial_number'
    )
);
No Comments on Specifying the Database Adapter to Use with the Zend Framework Db_NoRecordExists and Db_RecordExists Validators

Leave a Reply

Your email address will not be published. Required fields are marked *