Documentation

Zend_Db_Table - Zend_Db

Zend_Db_Table

Introduction

The Zend_Db_Table class is an object-oriented interface to database tables. It provides methods for many common operations on tables. The base class is extensible, so you can add custom logic.

The Zend_Db_Table solution is an implementation of the » Table Data Gateway pattern. The solution also includes a class that implements the » Row Data Gateway pattern.

Using Zend_Db_Table as a concrete class

As of Zend Framework 1.9, you can instantiate Zend_Db_Table. This added benefit is that you do not have to extend a base class and configure it to do simple operations such as selecting, inserting, updating and deleteing on a single table. below is an example of the simplest of use cases.

Example #1 Declaring a table class with just the string name

  1. Zend_Db_Table::setDefaultAdapter($dbAdapter);
  2. $bugTable = new Zend_Db_Table('bug');

The above example represents the simplest of use cases. Make not of all the options describe below for configuring Zend_Db_Table tables. If you want to be able to use the concrete usage case, in addition to the more complex relationhip features, see the Zend_Db_Table_Definition documentation.

Defining a Table Class

For each table in your database that you want to access, define a class that extends Zend_Db_Table_Abstract.

Defining the Table Name and Schema

Declare the database table for which this class is defined, using the protected variable $_name. This is a string, and must contain the name of the table spelled as it appears in the database.

Example #2 Declaring a table class with explicit table name

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4. }

If you don't specify the table name, it defaults to the name of the class. If you rely on this default, the class name must match the spelling of the table name as it appears in the database.

Example #3 Declaring a table class with implicit table name

  1. class bugs extends Zend_Db_Table_Abstract
  2. {
  3.     // table name matches class name
  4. }

You can also declare the schema for the table, either with the protected variable $_schema, or with the schema prepended to the table name in the $_name property. Any schema specified with the $_name property takes precedence over a schema specified with the $_schema property. In some RDBMS brands, the term for schema is "database" or "tablespace," but it is used similarly.

Example #4 Declaring a table class with schema

  1. // First alternative:
  2. class Bugs extends Zend_Db_Table_Abstract
  3. {
  4.     protected $_schema = 'bug_db';
  5.     protected $_name   = 'bugs';
  6. }
  7.  
  8. // Second alternative:
  9. class Bugs extends Zend_Db_Table_Abstract
  10. {
  11.     protected $_name = 'bug_db.bugs';
  12. }
  13.  
  14. // If schemas are specified in both $_name and $_schema, the one
  15. // specified in $_name takes precedence:
  16.  
  17. class Bugs extends Zend_Db_Table_Abstract
  18. {
  19.     protected $_name   = 'bug_db.bugs';
  20.     protected $_schema = 'ignored';
  21. }

The schema and table names may also be specified via constructor configuration directives, which override any default values specified with the $_name and $_schema properties. A schema specification given with the name directive overrides any value provided with the schema option.

Example #5 Declaring table and schema names upon instantiation

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3. }
  4.  
  5. // First alternative:
  6.  
  7. $tableBugs = new Bugs(array('name' => 'bugs', 'schema' => 'bug_db'));
  8.  
  9. // Second alternative:
  10.  
  11. $tableBugs = new Bugs(array('name' => 'bug_db.bugs'));
  12.  
  13. // If schemas are specified in both 'name' and 'schema', the one
  14. // specified in 'name' takes precedence:
  15.  
  16. $tableBugs = new Bugs(array('name' => 'bug_db.bugs',
  17.                             'schema' => 'ignored'));

If you don't specify the schema name, it defaults to the schema to which your database adapter instance is connected.

Defining the Table Primary Key

Every table must have a primary key. You can declare the column for the primary key using the protected variable $_primary. This is either a string that names the single column for the primary key, or else it is an array of column names if your primary key is a compound key.

Example #6 Example of specifying the primary key

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4.     protected $_primary = 'bug_id';
  5. }

If you don't specify the primary key, Zend_Db_Table_Abstract tries to discover the primary key based on the information provided by the describeTable()´ method.

Note: Every table class must know which columns can be used to address rows uniquely. If no primary key columns are specified in the table class definition or the table constructor arguments, or discovered in the table metadata provided by describeTable(), then the table cannot be used with Zend_Db_Table.

Overriding Table Setup Methods

When you create an instance of a Table class, the constructor calls a set of protected methods that initialize metadata for the table. You can extend any of these methods to define metadata explicitly. Remember to call the method of the same name in the parent class at the end of your method.

Example #7 Example of overriding the _setupTableName() method

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected function _setupTableName()
  4.     {
  5.         $this->_name = 'bugs';
  6.         parent::_setupTableName();
  7.     }
  8. }

The setup methods you can override are the following:

  • _setupDatabaseAdapter() checks that an adapter has been provided; gets a default adapter from the registry if needed. By overriding this method, you can set a database adapter from some other source.

  • _setupTableName() defaults the table name to the name of the class. By overriding this method, you can set the table name before this default behavior runs.

  • _setupMetadata() sets the schema if the table name contains the pattern "schema.table"; calls describeTable() to get metadata information; defaults the $_cols array to the columns reported by describeTable(). By overriding this method, you can specify the columns.

  • _setupPrimaryKey() defaults the primary key columns to those reported by describeTable(); checks that the primary key columns are included in the $_cols array. By overriding this method, you can specify the primary key columns.

Table initialization

If application-specific logic needs to be initialized when a Table class is constructed, you can select to move your tasks to the init() method, which is called after all Table metadata has been processed. This is recommended over the __construct() method if you do not need to alter the metadata in any programmatic way.

Example #8 Example usage of init() method

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_observer;
  4.  
  5.     public function init()
  6.     {
  7.         $this->_observer = new MyObserverClass();
  8.     }
  9. }

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 #9 Example of constructing a Table using an Adapter object

  1. $db = Zend_Db::factory('PDO_MYSQL', $options);
  2.  
  3. $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 #10 Example of constructing a Table using a the Default Adapter

  1. $db = Zend_Db::factory('PDO_MYSQL', $options);
  2. Zend_Db_Table_Abstract::setDefaultAdapter($db);
  3.  
  4. // Later...
  5.  
  6. $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 #11 Example of constructing a Table using a Registry key

  1. $db = Zend_Db::factory('PDO_MYSQL', $options);
  2. Zend_Registry::set('my_db', $db);
  3.  
  4. // Later...
  5.  
  6. $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.

Inserting Rows to a Table

You can use the Table object to insert rows into the database table on which the Table object is based. Use the insert() method of your Table object. The argument is an associative array, mapping column names to values.

Example #12 Example of inserting to a Table

  1. $table = new Bugs();
  2.  
  3. $data = array(
  4.     'created_on'      => '2007-03-22',
  5.     'bug_description' => 'Something wrong',
  6.     'bug_status'      => 'NEW'
  7. );
  8.  
  9. $table->insert($data);

By default, the values in your data array are inserted as literal values, using parameters. If you need them to be treated as SQL expressions, you must make sure they are distinct from plain strings. Use an object of type Zend_Db_Expr to do this.

Example #13 Example of inserting expressions to a Table

  1. $table = new Bugs();
  2.  
  3. $data = array(
  4.     'created_on'      => new Zend_Db_Expr('CURDATE()'),
  5.     'bug_description' => 'Something wrong',
  6.     'bug_status'      => 'NEW'
  7. );

In the examples of inserting rows above, it is assumed that the table has an auto-incrementing primary key. This is the default behavior of Zend_Db_Table_Abstract, but there are other types of primary keys as well. The following sections describe how to support different types of primary keys.

Using a Table with an Auto-incrementing Key

An auto-incrementing primary key generates a unique integer value for you if you omit the primary key column from your SQL INSERT statement.

In Zend_Db_Table_Abstract, if you define the protected variable $_sequence to be the Boolean value TRUE, then the class assumes that the table has an auto-incrementing primary key.

Example #14 Example of declaring a Table with auto-incrementing primary key

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4.  
  5.     // This is the default in the Zend_Db_Table_Abstract class;
  6.     // you do not need to define this.
  7.     protected $_sequence = true;
  8. }

MySQL, Microsoft SQL Server, and SQLite are examples of RDBMS brands that support auto-incrementing primary keys.

PostgreSQL has a SERIAL notation that implicitly defines a sequence based on the table and column name, and uses the sequence to generate key values for new rows. IBM DB2 has an IDENTITY notation that works similarly. If you use either of these notations, treat your Zend_Db_Table class as having an auto-incrementing column with respect to declaring the $_sequence member as TRUE.

Using a Table with a Sequence

A sequence is a database object that generates a unique value, which can be used as a primary key value in one or more tables of the database.

If you define $_sequence to be a string, then Zend_Db_Table_Abstract assumes the string to name a sequence object in the database. The sequence is invoked to generate a new value, and this value is used in the INSERT operation.

Example #15 Example of declaring a Table with a sequence

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4.  
  5.     protected $_sequence = 'bug_sequence';
  6. }

Oracle, PostgreSQL, and IBM DB2 are examples of RDBMS brands that support sequence objects in the database.

PostgreSQL and IBM DB2 also have syntax that defines sequences implicitly and associated with columns. If you use this notation, treat the table as having an auto-incrementing key column. Define the sequence name as a string only in cases where you would invoke the sequence explicitly to get the next key value.

Using a Table with a Natural Key

Some tables have a natural key. This means that the key is not automatically generated by the table or by a sequence. You must specify the value for the primary key in this case.

If you define the $_sequence to be the Boolean value FALSE, then Zend_Db_Table_Abstract assumes that the table has a natural primary key. You must provide values for the primary key columns in the array of data to the insert() method, or else this method throws a Zend_Db_Table_Exception.

Example #16 Example of declaring a Table with a natural key

  1. class BugStatus extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bug_status';
  4.  
  5.     protected $_sequence = false;
  6. }

Note: All RDBMS brands support tables with natural keys. Examples of tables that are often declared as having natural keys are lookup tables, intersection tables in many-to-many relationships, or most tables with compound primary keys.

Updating Rows in a Table

You can update rows in a database table using the update() method of a Table class. This method takes two arguments: an associative array of columns to change and new values to assign to these columns; and an SQL expression that is used in a WHERE clause, as criteria for the rows to change in the UPDATE operation.

Example #17 Example of updating rows in a Table

  1. $table = new Bugs();
  2.  
  3. $data = array(
  4.     'updated_on'      => '2007-03-23',
  5.     'bug_status'      => 'FIXED'
  6. );
  7.  
  8. $where = $table->getAdapter()->quoteInto('bug_id = ?', 1234);
  9.  
  10. $table->update($data, $where);

Since the table update() method proxies to the database adapter update() method, the second argument can be an array of SQL expressions. The expressions are combined as Boolean terms using an AND operator.

Note: The values and identifiers in the SQL expression are not quoted for you. If you have values or identifiers that require quoting, you are responsible for doing this. Use the quote(), quoteInto(), and quoteIdentifier() methods of the database adapter.

Deleting Rows from a Table

You can delete rows from a database table using the delete() method. This method takes one argument, which is an SQL expression that is used in a WHERE clause, as criteria for the rows to delete.

Example #18 Example of deleting rows from a Table

  1. $table = new Bugs();
  2.  
  3. $where = $table->getAdapter()->quoteInto('bug_id = ?', 1235);
  4.  
  5. $table->delete($where);

Since the table delete() method proxies to the database adapter delete() method, the argument can also be an array of SQL expressions. The expressions are combined as Boolean terms using an AND operator.

Note: The values and identifiers in the SQL expression are not quoted for you. If you have values or identifiers that require quoting, you are responsible for doing this. Use the quote(), quoteInto(), and quoteIdentifier() methods of the database adapter.

Finding Rows by Primary Key

You can query the database table for rows matching specific values in the primary key, using the find() method. The first argument of this method is either a single value or an array of values to match against the primary key of the table.

Example #19 Example of finding rows by primary key values

  1. $table = new Bugs();
  2.  
  3. // Find a single row
  4. // Returns a Rowset
  5. $rows = $table->find(1234);
  6.  
  7. // Find multiple rows
  8. // Also returns a Rowset
  9. $rows = $table->find(array(1234, 5678));

If you specify a single value, the method returns at most one row, because a primary key cannot have duplicate values and there is at most one row in the database table matching the value you specify. If you specify multiple values in an array, the method returns at most as many rows as the number of distinct values you specify.

The find() method might return fewer rows than the number of values you specify for the primary key, if some of the values don't match any rows in the database table. The method even may return zero rows. Because the number of rows returned is variable, the find() method returns an object of type Zend_Db_Table_Rowset_Abstract.

If the primary key is a compound key, that is, it consists of multiple columns, you can specify the additional columns as additional arguments to the find() method. You must provide as many arguments as the number of columns in the table's primary key.

To find multiple rows from a table with a compound primary key, provide an array for each of the arguments. All of these arrays must have the same number of elements. The values in each array are formed into tuples in order; for example, the first element in all the array arguments define the first compound primary key value, then the second elements of all the arrays define the second compound primary key value, and so on.

Example #20 Example of finding rows by compound primary key values

The call to find() below to match multiple rows can match two rows in the database. The first row must have primary key value (1234, 'ABC'), and the second row must have primary key value (5678, 'DEF').

  1. class BugsProducts extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs_products';
  4.     protected $_primary = array('bug_id', 'product_id');
  5. }
  6.  
  7. $table = new BugsProducts();
  8.  
  9. // Find a single row with a compound primary key
  10. // Returns a Rowset
  11. $rows = $table->find(1234, 'ABC');
  12.  
  13. // Find multiple rows with compound primary keys
  14. // Also returns a Rowset
  15. $rows = $table->find(array(1234, 5678), array('ABC', 'DEF'));

Querying for a Set of Rows

Select API

Warning

The API for fetch operations has been superseded to allow a Zend_Db_Table_Select object to modify the query. However, the deprecated usage of the fetchRow() and fetchAll() methods will continue to work without modification.

The following statements are all legal and functionally identical, however it is recommended to update your code to take advantage of the new usage where possible.

  1. /**
  2. * Fetching a rowset
  3. */
  4. $rows = $table->fetchAll(
  5.     'bug_status = "NEW"',
  6.     'bug_id ASC',
  7.     10,
  8.     0
  9.     );
  10. $rows = $table->fetchAll(
  11.     $table->select()
  12.         ->where('bug_status = ?', 'NEW')
  13.         ->order('bug_id ASC')
  14.         ->limit(10, 0)
  15.     );
  16. // or with binding
  17. $rows = $table->fetchAll(
  18.     $table->select()
  19.         ->where('bug_status = :status')
  20.         ->bind(array(':status'=>'NEW')
  21.         ->order('bug_id ASC')
  22.         ->limit(10, 0)
  23.     );
  24.  
  25. /**
  26. * Fetching a single row
  27. */
  28. $row = $table->fetchRow(
  29.     'bug_status = "NEW"',
  30.     'bug_id ASC'
  31.     );
  32. $row = $table->fetchRow(
  33.     $table->select()
  34.         ->where('bug_status = ?', 'NEW')
  35.         ->order('bug_id ASC')
  36.     );
  37. // or with binding
  38. $row = $table->fetchRow(
  39.     $table->select()
  40.         ->where('bug_status = :status')
  41.         ->bind(array(':status'=>'NEW')
  42.         ->order('bug_id ASC')
  43.     );

The Zend_Db_Table_Select object is an extension of the Zend_Db_Select object that applies specific restrictions to a query. The enhancements and restrictions are:

  • You can elect to return a subset of columns within a fetchRow or fetchAll query. This can provide optimization benefits where returning a large set of results for all columns is not desirable.

  • You can specify columns that evaluate expressions from within the selected table. However this will mean that the returned row or rowset will be readOnly and cannot be used for save() operations. A Zend_Db_Table_Row with readOnly status will throw an exception if a save() operation is attempted.

  • You can allow JOIN clauses on a select to allow multi-table lookups.

  • You can not specify columns from a JOINed tabled to be returned in a row or rowset. Doing so will trigger a PHP error. This was done to ensure the integrity of the Zend_Db_Table is retained. i.e. A Zend_Db_Table_Row should only reference columns derived from its parent table.

Example #21 Simple usage

  1. $table = new Bugs();
  2.  
  3. $select = $table->select();
  4. $select->where('bug_status = ?', 'NEW');
  5.  
  6. $rows = $table->fetchAll($select);

Fluent interfaces are implemented across the component, so this can be rewritten this in a more abbreviated form.

Example #22 Example of fluent interface

  1. $table = new Bugs();
  2.  
  3. $rows =
  4.     $table->fetchAll($table->select()->where('bug_status = ?', 'NEW'));

Fetching a rowset

You can query for a set of rows using any criteria other than the primary key values, using the fetchAll() method of the Table class. This method returns an object of type Zend_Db_Table_Rowset_Abstract.

Example #23 Example of finding rows by an expression

  1. $table = new Bugs();
  2.  
  3. $select = $table->select()->where('bug_status = ?', 'NEW');
  4.  
  5. $rows = $table->fetchAll($select);

You may also pass sorting criteria in an ORDER BY clause, as well as count and offset integer values, used to make the query return a specific subset of rows. These values are used in a LIMIT clause, or in equivalent logic for RDBMS brands that do not support the LIMIT syntax.

Example #24 Example of finding rows by an expression

  1. $table = new Bugs();
  2.  
  3. $order  = 'bug_id';
  4.  
  5. // Return the 21st through 30th rows
  6. $count  = 10;
  7. $offset = 20;
  8.  
  9. $select = $table->select()->where('bug_status = ?', 'NEW')
  10.                           ->order($order)
  11.                           ->limit($count, $offset);
  12.  
  13. $rows = $table->fetchAll($select);

All of the arguments above are optional. If you omit the ORDER clause, the result set includes rows from the table in an unpredictable order. If no LIMIT clause is set, you retrieve every row in the table that matches the WHERE clause.

Advanced usage

For more specific and optimized requests, you may wish to limit the number of columns returned in a row or rowset. This can be achieved by passing a FROM clause to the select object. The first argument in the FROM clause is identical to that of a Zend_Db_Select object with the addition of being able to pass an instance of Zend_Db_Table_Abstract and have it automatically determine the table name.

Example #25 Retrieving specific columns

  1. $table = new Bugs();
  2.  
  3. $select = $table->select();
  4. $select->from($table, array('bug_id', 'bug_description'))
  5.        ->where('bug_status = ?', 'NEW');
  6.  
  7. $rows = $table->fetchAll($select);
Important

The rowset contains rows that are still 'valid' - they simply contain a subset of the columns of a table. If a save() method is called on a partial row then only the fields available will be modified.

You can also specify expressions within a FROM clause and have these returned as a readOnly row or rowset. In this example we will return a rows from the bugs table that show an aggregate of the number of new bugs reported by individuals. Note the GROUP clause. The 'count' column will be made available to the row for evaluation and can be accessed as if it were part of the schema.

Example #26 Retrieving expressions as columns

  1. $table = new Bugs();
  2.  
  3. $select = $table->select();
  4. $select->from($table,
  5.               array('COUNT(reported_by) as `count`', 'reported_by'))
  6.        ->where('bug_status = ?', 'NEW')
  7.        ->group('reported_by');
  8.  
  9. $rows = $table->fetchAll($select);

You can also use a lookup as part of your query to further refine your fetch operations. In this example the accounts table is queried as part of a search for all new bugs reported by 'Bob'.

Example #27 Using a lookup table to refine the results of fetchAll()

  1. $table = new Bugs();
  2.  
  3. // retrieve with from part set, important when joining
  4. $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
  5. $select->setIntegrityCheck(false)
  6.        ->where('bug_status = ?', 'NEW')
  7.        ->join('accounts', 'accounts.account_name = bugs.reported_by')
  8.        ->where('accounts.account_name = ?', 'Bob');
  9.  
  10. $rows = $table->fetchAll($select);

The Zend_Db_Table_Select is primarily used to constrain and validate so that it may enforce the criteria for a legal SELECT query. However there may be certain cases where you require the flexibility of the Zend_Db_Table_Row component and do not require a writable or deletable row. for this specific user case, it is possible to retrieve a row or rowset by passing a FALSE value to setIntegrityCheck(). The resulting row or rowset will be returned as a 'locked' row (meaning the save(), delete() and any field-setting methods will throw an exception).

Example #28 Removing the integrity check on Zend_Db_Table_Select to allow JOINed rows

  1. $table = new Bugs();
  2.  
  3. $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
  4.                 ->setIntegrityCheck(false);
  5. $select->where('bug_status = ?', 'NEW')
  6.        ->join('accounts',
  7.               'accounts.account_name = bugs.reported_by',
  8.               'account_name')
  9.        ->where('accounts.account_name = ?', 'Bob');
  10.  
  11. $rows = $table->fetchAll($select);

Querying for a Single Row

You can query for a single row using criteria similar to that of the fetchAll() method.

Example #29 Example of finding a single row by an expression

  1. $table = new Bugs();
  2.  
  3. $select  = $table->select()->where('bug_status = ?', 'NEW')
  4.                            ->order('bug_id');
  5.  
  6. $row = $table->fetchRow($select);

This method returns an object of type Zend_Db_Table_Row_Abstract. If the search criteria you specified match no rows in the database table, then fetchRow() returns PHP's NULL value.

Retrieving Table Metadata Information

The Zend_Db_Table_Abstract class provides some information about its metadata. The info() method returns an array structure with information about the table, its columns and primary key, and other metadata.

Example #30 Example of getting the table name

  1. $table = new Bugs();
  2.  
  3. $info = $table->info();
  4.  
  5. echo "The table name is " . $info['name'] . "\n";

The keys of the array returned by the info() method are described below:

  • name => the name of the table.

  • cols => an array, naming the columns of the table.

  • primary => an array, naming the columns in the primary key.

  • metadata => an associative array, mapping column names to information about the columns. This is the information returned by the describeTable() method.

  • rowClass => the name of the concrete class used for Row objects returned by methods of this table instance. This defaults to Zend_Db_Table_Row.

  • rowsetClass => the name of the concrete class used for Rowset objects returned by methods of this table instance. This defaults to Zend_Db_Table_Rowset.

  • referenceMap => an associative array, with information about references from this table to any parent tables. See this chapter.

  • dependentTables => an array of class names of tables that reference this table. See this chapter.

  • schema => the name of the schema (or database or tablespace) for this table.

Caching Table Metadata

By default, Zend_Db_Table_Abstract queries the underlying database for table metadata whenever that data is needed to perform table operations. The table object fetches the table metadata from the database using the adapter's describeTable() method. Operations requiring this introspection include:

  • insert()

  • find()

  • info()

In some circumstances, particularly when many table objects are instantiated against the same database table, querying the database for the table metadata for each instance may be undesirable from a performance standpoint. In such cases, users may benefit by caching the table metadata retrieved from the database.

There are two primary ways in which a user may take advantage of table metadata caching:

  • Call Zend_Db_Table_Abstract::setDefaultMetadataCache() - This allows a developer to once set the default cache object to be used for all table classes.

  • Configure Zend_Db_Table_Abstract::__construct() - This allows a developer to set the cache object to be used for a particular table class instance.

In both cases, the cache specification must be either NULL (i.e., no cache used) or an instance of Zend_Cache_Core. The methods may be used in conjunction when it is desirable to have both a default metadata cache and the ability to change the cache for individual table objects.

Example #31 Using a Default Metadata Cache for all Table Objects

The following code demonstrates how to set a default metadata cache to be used for all table objects:

  1. // First, set up the Cache
  2. $frontendOptions = array(
  3.     'automatic_serialization' => true
  4.     );
  5.  
  6. $backendOptions  = array(
  7.     'cache_dir'                => 'cacheDir'
  8.     );
  9.  
  10. $cache = Zend_Cache::factory('Core',
  11.                              'File',
  12.                              $frontendOptions,
  13.                              $backendOptions);
  14.  
  15. // Next, set the cache to be used with all table objects
  16. Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
  17.  
  18. // A table class is also needed
  19. class Bugs extends Zend_Db_Table_Abstract
  20. {
  21.     // ...
  22. }
  23.  
  24. // Each instance of Bugs now uses the default metadata cache
  25. $bugs = new Bugs();

Example #32 Using a Metadata Cache for a Specific Table Object

The following code demonstrates how to set a metadata cache for a specific table object instance:

  1. // First, set up the Cache
  2. $frontendOptions = array(
  3.     'automatic_serialization' => true
  4.     );
  5.  
  6. $backendOptions  = array(
  7.     'cache_dir'                => 'cacheDir'
  8.     );
  9.  
  10. $cache = Zend_Cache::factory('Core',
  11.                              'File',
  12.                              $frontendOptions,
  13.                              $backendOptions);
  14.  
  15. // A table class is also needed
  16. class Bugs extends Zend_Db_Table_Abstract
  17. {
  18.     // ...
  19. }
  20.  
  21. // Configure an instance upon instantiation
  22. $bugs = new Bugs(array('metadataCache' => $cache));

Note: Automatic Serialization with the Cache Frontend
Since the information returned from the adapter's describeTable() method is an array, ensure that the automatic_serialization option is set to TRUE for the Zend_Cache_Core frontend.

Though the above examples use Zend_Cache_Backend_File, developers may use whatever cache backend is appropriate for the situation. Please see Zend_Cache for more information.

Hardcoding Table Metadata

To take metadata caching a step further, you can also choose to hardcode metadata. In this particular case, however, any changes to the table schema will require a change in your code. As such, it is only recommended for those who are optimizing for production usage.

The metadata structure is as follows:

  1. protected $_metadata = array(
  2.     '<column_name>' => array(
  3.         'SCHEMA_NAME'      => <string>,
  4.         'TABLE_NAME'       => <string>,
  5.         'COLUMN_NAME'      => <string>,
  6.         'COLUMN_POSITION'  => <int>,
  7.         'DATA_TYPE'        => <string>,
  8.         'DEFAULT'          => NULL|<value>,
  9.         'NULLABLE'         => <bool>,
  10.         'LENGTH'           => <string - length>,
  11.         'SCALE'            => NULL|<value>,
  12.         'PRECISION'        => NULL|<value>,
  13.         'UNSIGNED'         => NULL|<bool>,
  14.         'PRIMARY'          => <bool>,
  15.         'PRIMARY_POSITION' => <int>,
  16.         'IDENTITY'         => <bool>,
  17.     ),
  18.     // additional columns...
  19. );

An easy way to get the appropriate values is to use the metadata cache, and then to deserialize values stored in the cache.

You can disable this optimization by turning of the metadataCacheInClass flag:

  1. // At instantiation:
  2. $bugs = new Bugs(array('metadataCacheInClass' => false));
  3.  
  4. // Or later:
  5. $bugs->setMetadataCacheInClass(false);

The flag is enabled by default, which ensures that the $_metadata array is only populated once per instance.

Customizing and Extending a Table Class

Using Custom Row or Rowset Classes

By default, methods of the Table class return a Rowset in instances of the concrete class Zend_Db_Table_Rowset, and Rowsets contain a collection of instances of the concrete class Zend_Db_Table_Row You can specify an alternative class to use for either of these, but they must be classes that extend Zend_Db_Table_Rowset_Abstract and Zend_Db_Table_Row_Abstract, respectively.

You can specify Row and Rowset classes using the Table constructor's options array, in keys 'rowClass' and 'rowsetClass' respectively. Specify the names of the classes using strings.

Example #33 Example of specifying the Row and Rowset classes

  1. class My_Row extends Zend_Db_Table_Row_Abstract
  2. {
  3.     ...
  4. }
  5.  
  6. class My_Rowset extends Zend_Db_Table_Rowset_Abstract
  7. {
  8.     ...
  9. }
  10.  
  11. $table = new Bugs(
  12.     array(
  13.         'rowClass'    => 'My_Row',
  14.         'rowsetClass' => 'My_Rowset'
  15.     )
  16. );
  17.  
  18. $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
  19.  
  20. // Returns an object of type My_Rowset,
  21. // containing an array of objects of type My_Row.
  22. $rows = $table->fetchAll($where);

You can change the classes by specifying them with the setRowClass() and setRowsetClass() methods. This applies to rows and rowsets created subsequently; it does not change the class of any row or rowset objects you have created previously.

Example #34 Example of changing the Row and Rowset classes

  1. $table = new Bugs();
  2.  
  3. $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
  4.  
  5. // Returns an object of type Zend_Db_Table_Rowset
  6. // containing an array of objects of type Zend_Db_Table_Row.
  7. $rowsStandard = $table->fetchAll($where);
  8.  
  9. $table->setRowClass('My_Row');
  10. $table->setRowsetClass('My_Rowset');
  11.  
  12. // Returns an object of type My_Rowset,
  13. // containing an array of objects of type My_Row.
  14. $rowsCustom = $table->fetchAll($where);
  15.  
  16. // The $rowsStandard object still exists, and it is unchanged.

For more information on the Row and Rowset classes, see this chapter and this one.

Defining Custom Logic for Insert, Update, and Delete

You can override the insert() and update() methods in your Table class. This gives you the opportunity to implement custom code that is executed before performing the database operation. Be sure to call the parent class method when you are done.

Example #35 Custom logic to manage timestamps

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4.  
  5.     public function insert(array $data)
  6.     {
  7.         // add a timestamp
  8.         if (empty($data['created_on'])) {
  9.             $data['created_on'] = time();
  10.         }
  11.         return parent::insert($data);
  12.     }
  13.  
  14.     public function update(array $data, $where)
  15.     {
  16.         // add a timestamp
  17.         if (empty($data['updated_on'])) {
  18.             $data['updated_on'] = time();
  19.         }
  20.         return parent::update($data, $where);
  21.     }
  22. }

You can also override the delete() method.

Define Custom Search Methods in Zend_Db_Table

You can implement custom query methods in your Table class, if you have frequent need to do queries against this table with specific criteria. Most queries can be written using fetchAll(), but this requires that you duplicate code to form the query conditions if you need to run the query in several places in your application. Therefore it can be convenient to implement a method in the Table class to perform frequently-used queries against this table.

Example #36 Custom method to find bugs by status

  1. class Bugs extends Zend_Db_Table_Abstract
  2. {
  3.     protected $_name = 'bugs';
  4.  
  5.     public function findByStatus($status)
  6.     {
  7.         $where = $this->getAdapter()->quoteInto('bug_status = ?', $status);
  8.         return $this->fetchAll($where, 'bug_id');
  9.     }
  10. }

Define Inflection in Zend_Db_Table

Some people prefer that the table class name match a table name in the RDBMS by using a string transformation called inflection.

For example, if your table class name is "BugsProducts", it would match the physical table in the database called "bugs_products", if you omit the explicit declaration of the $_name class property. In this inflection mapping, the class name spelled in "CamelCase" format would be transformed to lower case, and words are separated with an underscore.

You can specify the database table name independently from the class name by declaring the table name with the $_name class property in each of your table classes.

Zend_Db_Table_Abstract performs no inflection to map the class name to the table name. If you omit the declaration of $_name in your table class, the class maps to a database table that matches the spelling of the class name exactly.

It is inappropriate to transform identifiers from the database, because this can lead to ambiguity or make some identifiers inaccessible. Using the SQL identifiers exactly as they appear in the database makes Zend_Db_Table_Abstract both simpler and more flexible.

If you prefer to use inflection, then you must implement the transformation yourself, by overriding the _setupTableName() method in your Table classes. One way to do this is to define an abstract class that extends Zend_Db_Table_Abstract, and then the rest of your tables extend your new abstract class.

Example #37 Example of an abstract table class that implements inflection

  1. abstract class MyAbstractTable extends Zend_Db_Table_Abstract
  2. {
  3.     protected function _setupTableName()
  4.     {
  5.         if (!$this->_name) {
  6.             $this->_name = myCustomInflector(get_class($this));
  7.         }
  8.         parent::_setupTableName();
  9.     }
  10. }
  11.  
  12. class BugsProducts extends MyAbstractTable
  13. {
  14. }

You are responsible for writing the functions to perform inflection transformation. Zend Framework does not provide such a function.

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts