jump to navigation

Using ZF’s Zend_Db_Table Module with Standalone PHP Applications August 7, 2012

Posted by Tournas Dimitrios in PHP, Zend Framework v1.10.

That’s the beauty of Zend Framework’s structure , using one (or more) of it’s modules as separate snippets into standalone PHP applications is really simple .  This framework implements many well proven design patterns to build loosely coupled PHP applications . No matter the size of the application you plan to build , it’s good to implement well proven architecture-design from the beginning . Who knows , a simple application might evolve into a complex structure in the future🙂 .
Today’s article will demonstrate the use of ZF’s database module , the Zend_Db_Table module , into a standalone PHP application . This module implements , behind the scenes , the “Table Data Gateway” design pattern (TDG) . This pattern , acts as a “Gateway” between our application and the database table , achieving separation  of domain logic from SQL statements . If that sounds complicated , allow me to attempt a second time . A PHP Class forms a Gateway  to the database-table , and the rest of the application needs to know nothing about SQL , and all the SQL that accesses the database (hope this second attempt was more descriptive) .

In the TDG pattern each database-table is represented by a PHP Class (usually the name of the Class reflects the name of the database-table )  . The Class provides methods for many common operations on tables , though this base class is extensible , so you can add custom logic . A practical example will shed more light into my thoughts .

set_include_path( 'C:\phpLib\library') ;
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance() ;

//Using Zend_Config to pass parameters into Db-connection
$config = new Zend_Config(
        'database' => array(
            'adapter' => 'Mysqli',
            'params'  => array(
                'host'     => '',
                'dbname'   => 'world',
                'username' => 'root',
                'password' => '',
$db = Zend_Db::factory($config->database);

// OR alternatively passing credentials hard-coded
 $db = Zend_Db::factory('Pdo_Mysql' ,  array(
    'host'     => '',
    'username' => 'root',
    'password' => '',
    'dbname'   => 'world'

try {
$db->getConnection() ;
class Country extends Zend_Db_Table_Abstract
   public function getAll()
      return $this->fetchAll();

$countries = new Country() ;
foreach($countries->getAll() as $values)
  echo $values['Name']."<br \>";

} catch (Zend_Db_Adapter_Exception $e) {

echo "<strong>Database connection failed :</strong>
	<li>Perhaps a failed login credential, or perhaps the RDBMS is not running</li>
" ;
} catch (Zend_Exception $e) {

echo "<b>Database connection failed :</b> <br \>
<li>perhaps factory() failed to load the specified Adapter class</li>" ;

Let’s  explain the code :

  • Line 2 : Setting the path of ZF’s  library location
  • Line 3 – 4 : Instantiation of the auto-loader . From now , we don’t have to define “require_once” statements anymore , as  auto-loading will handle all the necessary steps for us .
  • Creating an instance of a database adapter Class using the static method Zend_Db::factory() by passing two arguments (the type of connection — PDO , Mysql , SQL3 …… — , the second argument is an array of all DB credentials ) .
  • Line 33 : Creating an instance of an Adapter class does not immediately connect to theRDBMS server . The Adapter saves the connection parameters, and makes the actual connection on demand, the first time you need to execute a query. This ensures that creating an Adapter object is quick and inexpensive . You can create an instance of an Adapter even if you are not certain that you need to run any database queries during the current request your application is serving . If you need to force the Adapter to connect to the RDBMS , use the getConnection() method . It can be useful to force the connection if you want to catch any exceptions it throws as a result of invalid account credentials , or other failure to connect to the RDBMS server . These exceptions are not thrown until the connection is made , so it can help simplify your application code if you handle the exceptions in one place , instead of at the time of the first query against the database .
  • Line 35 – 41 : The Class that implements the TDG design pattern (it’s name reflects the name of the database-table we want to access ) .
  • Line 43 – 47 : Instantiation of the “Country” Class and accessing all values (looping through it’s content )
  • Line 6 – 22 : A good practice is to not hard-code credentials into the PHP file , an external configuration file should hold all these details . ZF’s   Zend_Config  module is proper to read external configuration files . Our code is now more portable .

It’s clearly shown in the previous code how the abstraction is achieved , there are no SQL statements defined into our PHP application (no spaghetti code ) . Our TDG pattern hides all the SQL logic .


No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s