1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.db.table">
4 <title>Zend_Db_Table</title>
6 <sect2 id="zend.db.table.introduction">
7 <title>Introduction</title>
10 The <classname>Zend_Db_Table</classname> class is an object-oriented interface to
11 database tables. It provides methods for many common operations on tables. The base
12 class is extensible, so you can add custom logic.
16 The <classname>Zend_Db_Table</classname> solution is an implementation of the
17 <ulink url="http://www.martinfowler.com/eaaCatalog/tableDataGateway.html">Table Data
18 Gateway</ulink> pattern. The solution also includes a class that implements the
19 <ulink url="http://www.martinfowler.com/eaaCatalog/rowDataGateway.html">Row Data
20 Gateway</ulink> pattern.
24 <sect2 id="zend.db.table.concrete">
25 <title>Using Zend_Db_Table as a concrete class</title>
28 As of Zend Framework 1.9, you can instantiate <classname>Zend_Db_Table</classname>. This
29 added benefit is that you do not have to extend a base class and configure it to do
30 simple operations such as selecting, inserting, updating and deleteing on a single
31 table. below is an example of the simplest of use cases.
34 <example id="zend.db.table.defining.concrete-instantiation.example1">
35 <title>Declaring a table class with just the string name</title>
37 <programlisting language="php"><![CDATA[
38 Zend_Db_Table::setDefaultAdapter($dbAdapter);
39 $bugTable = new Zend_Db_Table('bug');
44 The above example represents the simplest of use cases. Make not of all the
45 options describe below for configuring <classname>Zend_Db_Table</classname> tables. If
46 you want to be able to use the concrete usage case, in addition to the more complex
47 relationhip features, see the <classname>Zend_Db_Table_Definition</classname>
52 <sect2 id="zend.db.table.defining">
53 <title>Defining a Table Class</title>
56 For each table in your database that you want to access, define a class that extends
57 <classname>Zend_Db_Table_Abstract</classname>.
60 <sect3 id="zend.db.table.defining.table-schema">
61 <title>Defining the Table Name and Schema</title>
64 Declare the database table for which this class is defined, using the protected
65 variable <varname>$_name</varname>. This is a string, and must contain the name of
66 the table spelled as it appears in the database.
69 <example id="zend.db.table.defining.table-schema.example1">
70 <title>Declaring a table class with explicit table name</title>
72 <programlisting language="php"><![CDATA[
73 class Bugs extends Zend_Db_Table_Abstract
75 protected $_name = 'bugs';
81 If you don't specify the table name, it defaults to the name of the class. If you
82 rely on this default, the class name must match the spelling of the table name as
83 it appears in the database.
86 <example id="zend.db.table.defining.table-schema.example">
87 <title>Declaring a table class with implicit table name</title>
89 <programlisting language="php"><![CDATA[
90 class bugs extends Zend_Db_Table_Abstract
92 // table name matches class name
98 You can also declare the schema for the table, either with the protected variable
99 <varname>$_schema</varname>, or with the schema prepended to the table name in the
100 <varname>$_name</varname> property. Any schema specified with the
101 <varname>$_name</varname> property takes precedence over a schema specified with the
102 <varname>$_schema</varname> property. In some <acronym>RDBMS</acronym> brands, the
103 term for schema is "database" or "tablespace," but it is used similarly.
106 <example id="zend.db.table.defining.table-schema.example3">
107 <title>Declaring a table class with schema</title>
109 <programlisting language="php"><![CDATA[
110 // First alternative:
111 class Bugs extends Zend_Db_Table_Abstract
113 protected $_schema = 'bug_db';
114 protected $_name = 'bugs';
117 // Second alternative:
118 class Bugs extends Zend_Db_Table_Abstract
120 protected $_name = 'bug_db.bugs';
123 // If schemas are specified in both $_name and $_schema, the one
124 // specified in $_name takes precedence:
126 class Bugs extends Zend_Db_Table_Abstract
128 protected $_name = 'bug_db.bugs';
129 protected $_schema = 'ignored';
135 The schema and table names may also be specified via constructor configuration
136 directives, which override any default values specified with the
137 <varname>$_name</varname> and <varname>$_schema</varname> properties. A schema
138 specification given with the <property>name</property> directive overrides any value
139 provided with the <property>schema</property> option.
142 <example id="zend.db.table.defining.table-schema.example.constructor">
143 <title>Declaring table and schema names upon instantiation</title>
145 <programlisting language="php"><![CDATA[
146 class Bugs extends Zend_Db_Table_Abstract
150 // First alternative:
152 $tableBugs = new Bugs(array('name' => 'bugs', 'schema' => 'bug_db'));
154 // Second alternative:
156 $tableBugs = new Bugs(array('name' => 'bug_db.bugs'));
158 // If schemas are specified in both 'name' and 'schema', the one
159 // specified in 'name' takes precedence:
161 $tableBugs = new Bugs(array('name' => 'bug_db.bugs',
162 'schema' => 'ignored'));
167 If you don't specify the schema name, it defaults to the schema to which your
168 database adapter instance is connected.
172 <sect3 id="zend.db.table.defining.primary-key">
173 <title>Defining the Table Primary Key</title>
176 Every table must have a primary key. You can declare the column for the primary key
177 using the protected variable <varname>$_primary</varname>. This is either a string
178 that names the single column for the primary key, or else it is an array of column
179 names if your primary key is a compound key.
182 <example id="zend.db.table.defining.primary-key.example">
183 <title>Example of specifying the primary key</title>
185 <programlisting language="php"><![CDATA[
186 class Bugs extends Zend_Db_Table_Abstract
188 protected $_name = 'bugs';
189 protected $_primary = 'bug_id';
195 If you don't specify the primary key, <classname>Zend_Db_Table_Abstract</classname>
196 tries to discover the primary key based on the information provided by the
197 <methodname>describeTable()</methodname>ยด method.
202 Every table class must know which columns can be used to address rows
203 uniquely. If no primary key columns are specified in the table class
204 definition or the table constructor arguments, or discovered in the table
205 metadata provided by <methodname>describeTable()</methodname>, then the table
206 cannot be used with <classname>Zend_Db_Table</classname>.
211 <sect3 id="zend.db.table.defining.setup">
212 <title>Overriding Table Setup Methods</title>
215 When you create an instance of a Table class, the constructor calls a set of
216 protected methods that initialize metadata for the table. You can extend any of
217 these methods to define metadata explicitly. Remember to call the method of the
218 same name in the parent class at the end of your method.
221 <example id="zend.db.table.defining.setup.example">
222 <title>Example of overriding the _setupTableName() method</title>
224 <programlisting language="php"><![CDATA[
225 class Bugs extends Zend_Db_Table_Abstract
227 protected function _setupTableName()
229 $this->_name = 'bugs';
230 parent::_setupTableName();
237 The setup methods you can override are the following:
243 <methodname>_setupDatabaseAdapter()</methodname> checks that an adapter has
244 been provided; gets a default adapter from the registry if needed. By
245 overriding this method, you can set a database adapter from some other
252 <methodname>_setupTableName()</methodname> defaults the table name to the
253 name of the class. By overriding this method, you can set the table name
254 before this default behavior runs.
260 <methodname>_setupMetadata()</methodname> sets the schema if the table name
261 contains the pattern "<command>schema.table</command>"; calls
262 <methodname>describeTable()</methodname> to get metadata information;
263 defaults the <varname>$_cols</varname> array to the columns reported by
264 <methodname>describeTable()</methodname>. By overriding this method, you can
271 <methodname>_setupPrimaryKey()</methodname> defaults the primary key columns
272 to those reported by <methodname>describeTable()</methodname>; checks that
273 the primary key columns are included in the <varname>$_cols</varname> array.
274 By overriding this method, you can specify the primary key columns.
280 <sect3 id="zend.db.table.initialization">
281 <title>Table initialization</title>
284 If application-specific logic needs to be initialized when a Table class is
285 constructed, you can select to move your tasks to the
286 <methodname>init()</methodname> method, which is called after all Table metadata has
287 been processed. This is recommended over the <methodname>__construct()</methodname>
288 method if you do not need to alter the metadata in any programmatic way.
291 <example id="zend.db.table.defining.init.usage.example">
292 <title>Example usage of init() method</title>
294 <programlisting language="php"><![CDATA[
295 class Bugs extends Zend_Db_Table_Abstract
297 protected $_observer;
299 public function init()
301 $this->_observer = new MyObserverClass();
309 <sect2 id="zend.db.table.constructing">
310 <title>Creating an Instance of a Table</title>
313 Before you use a Table class, create an instance using its constructor. The
314 constructor's argument is an array of options. The most important option to a Table
315 constructor is the database adapter instance, representing a live connection to an
316 <acronym>RDBMS</acronym>. There are three ways of specifying the database adapter to a
317 Table class, and these three ways are described below:
320 <sect3 id="zend.db.table.constructing.adapter">
321 <title>Specifying a Database Adapter</title>
324 The first way to provide a database adapter to a Table class is by passing it as an
325 object of type <classname>Zend_Db_Adapter_Abstract</classname> in the options array,
326 identified by the key '<property>db</property>'.
329 <example id="zend.db.table.constructing.adapter.example">
330 <title>Example of constructing a Table using an Adapter object</title>
332 <programlisting language="php"><![CDATA[
333 $db = Zend_Db::factory('PDO_MYSQL', $options);
335 $table = new Bugs(array('db' => $db));
340 <sect3 id="zend.db.table.constructing.default-adapter">
341 <title>Setting a Default Database Adapter</title>
344 The second way to provide a database adapter to a Table class is by declaring an
345 object of type <classname>Zend_Db_Adapter_Abstract</classname> to be a default
346 database adapter for all subsequent instances of Tables in your application. You can
347 do this with the static method
348 <methodname>Zend_Db_Table_Abstract::setDefaultAdapter()</methodname>. The argument
349 is an object of type <classname>Zend_Db_Adapter_Abstract</classname>.
352 <example id="zend.db.table.constructing.default-adapter.example">
353 <title>Example of constructing a Table using a the Default Adapter</title>
355 <programlisting language="php"><![CDATA[
356 $db = Zend_Db::factory('PDO_MYSQL', $options);
357 Zend_Db_Table_Abstract::setDefaultAdapter($db);
366 It can be convenient to create the database adapter object in a central place of
367 your application, such as the bootstrap, and then store it as the default adapter.
368 This gives you a means to ensure that the adapter instance is the same throughout
369 your application. However, setting a default adapter is limited to a single adapter
374 <sect3 id="zend.db.table.constructing.registry">
375 <title>Storing a Database Adapter in the Registry</title>
378 The third way to provide a database adapter to a Table class is by passing a string
379 in the options array, also identified by the '<property>db</property>' key. The
380 string is used as a key to the static <classname>Zend_Registry</classname> instance,
381 where the entry at that key is an object of type
382 <classname>Zend_Db_Adapter_Abstract</classname>.
385 <example id="zend.db.table.constructing.registry.example">
386 <title>Example of constructing a Table using a Registry key</title>
388 <programlisting language="php"><![CDATA[
389 $db = Zend_Db::factory('PDO_MYSQL', $options);
390 Zend_Registry::set('my_db', $db);
394 $table = new Bugs(array('db' => 'my_db'));
399 Like setting the default adapter, this gives you the means to ensure that the same
400 adapter instance is used throughout your application. Using the registry is more
401 flexible, because you can store more than one adapter instance. A given adapter
402 instance is specific to a certain <acronym>RDBMS</acronym> brand and database
403 instance. If your application needs access to multiple databases or even multiple
404 database brands, then you need to use multiple adapters.
409 <sect2 id="zend.db.table.insert">
410 <title>Inserting Rows to a Table</title>
413 You can use the Table object to insert rows into the database table on which the Table
414 object is based. Use the <methodname>insert()</methodname> method of your Table object.
415 The argument is an associative array, mapping column names to values.
418 <example id="zend.db.table.insert.example">
419 <title>Example of inserting to a Table</title>
421 <programlisting language="php"><![CDATA[
425 'created_on' => '2007-03-22',
426 'bug_description' => 'Something wrong',
427 'bug_status' => 'NEW'
430 $table->insert($data);
435 By default, the values in your data array are inserted as literal values, using
436 parameters. If you need them to be treated as <acronym>SQL</acronym> expressions, you
437 must make sure they are distinct from plain strings. Use an object of type
438 <classname>Zend_Db_Expr</classname> to do this.
441 <example id="zend.db.table.insert.example-expr">
442 <title>Example of inserting expressions to a Table</title>
444 <programlisting language="php"><![CDATA[
448 'created_on' => new Zend_Db_Expr('CURDATE()'),
449 'bug_description' => 'Something wrong',
450 'bug_status' => 'NEW'
456 In the examples of inserting rows above, it is assumed that the table has an
457 auto-incrementing primary key. This is the default behavior of
458 <classname>Zend_Db_Table_Abstract</classname>, but there are other types of primary keys
459 as well. The following sections describe how to support different types of primary keys.
462 <sect3 id="zend.db.table.insert.key-auto">
463 <title>Using a Table with an Auto-incrementing Key</title>
466 An auto-incrementing primary key generates a unique integer value for you if you
467 omit the primary key column from your <acronym>SQL</acronym>
468 <constant>INSERT</constant> statement.
472 In <classname>Zend_Db_Table_Abstract</classname>, if you define the protected
473 variable <varname>$_sequence</varname> to be the Boolean value
474 <constant>TRUE</constant>, then the class assumes that the table has an
475 auto-incrementing primary key.
478 <example id="zend.db.table.insert.key-auto.example">
479 <title>Example of declaring a Table with auto-incrementing primary key</title>
481 <programlisting language="php"><![CDATA[
482 class Bugs extends Zend_Db_Table_Abstract
484 protected $_name = 'bugs';
486 // This is the default in the Zend_Db_Table_Abstract class;
487 // you do not need to define this.
488 protected $_sequence = true;
494 MySQL, Microsoft <acronym>SQL</acronym> Server, and SQLite are examples of
495 <acronym>RDBMS</acronym> brands that support auto-incrementing primary keys.
499 PostgreSQL has a <constant>SERIAL</constant> notation that implicitly defines a
500 sequence based on the table and column name, and uses the sequence to generate key
501 values for new rows. <acronym>IBM</acronym> <acronym>DB2</acronym> has an
502 <constant>IDENTITY</constant> notation that works similarly. If you use either of
503 these notations, treat your <classname>Zend_Db_Table</classname> class as having an
504 auto-incrementing column with respect to declaring the <varname>$_sequence</varname>
505 member as <constant>TRUE</constant>.
509 <sect3 id="zend.db.table.insert.key-sequence">
510 <title>Using a Table with a Sequence</title>
513 A sequence is a database object that generates a unique value, which can be used
514 as a primary key value in one or more tables of the database.
518 If you define <varname>$_sequence</varname> to be a string, then
519 <classname>Zend_Db_Table_Abstract</classname> assumes the string to name a sequence
520 object in the database. The sequence is invoked to generate a new value, and this
521 value is used in the <constant>INSERT</constant> operation.
524 <example id="zend.db.table.insert.key-sequence.example">
525 <title>Example of declaring a Table with a sequence</title>
527 <programlisting language="php"><![CDATA[
528 class Bugs extends Zend_Db_Table_Abstract
530 protected $_name = 'bugs';
532 protected $_sequence = 'bug_sequence';
538 Oracle, PostgreSQL, and <acronym>IBM</acronym> <acronym>DB2</acronym> are examples
539 of <acronym>RDBMS</acronym> brands that support sequence objects in the database.
543 PostgreSQL and <acronym>IBM</acronym> <acronym>DB2</acronym> also have syntax that
544 defines sequences implicitly and associated with columns. If you use this notation,
545 treat the table as having an auto-incrementing key column. Define the sequence name
546 as a string only in cases where you would invoke the sequence explicitly to get the
551 <sect3 id="zend.db.table.insert.key-natural">
552 <title>Using a Table with a Natural Key</title>
555 Some tables have a natural key. This means that the key is not automatically
556 generated by the table or by a sequence. You must specify the value for the primary
561 If you define the <varname>$_sequence</varname> to be the Boolean value
562 <constant>FALSE</constant>, then <classname>Zend_Db_Table_Abstract</classname>
563 assumes that the table has a natural primary key. You must provide values for the
564 primary key columns in the array of data to the <methodname>insert()</methodname>
565 method, or else this method throws a <classname>Zend_Db_Table_Exception</classname>.
568 <example id="zend.db.table.insert.key-natural.example">
569 <title>Example of declaring a Table with a natural key</title>
571 <programlisting language="php"><![CDATA[
572 class BugStatus extends Zend_Db_Table_Abstract
574 protected $_name = 'bug_status';
576 protected $_sequence = false;
583 All <acronym>RDBMS</acronym> brands support tables with natural keys. Examples
584 of tables that are often declared as having natural keys are lookup tables,
585 intersection tables in many-to-many relationships, or most tables with compound
592 <sect2 id="zend.db.table.update">
593 <title>Updating Rows in a Table</title>
596 You can update rows in a database table using the <methodname>update()</methodname>
597 method of a Table class. This method takes two arguments: an associative array of
598 columns to change and new values to assign to these columns; and an
599 <acronym>SQL</acronym> expression that is used in a <constant>WHERE</constant> clause,
600 as criteria for the rows to change in the <constant>UPDATE</constant> operation.
603 <example id="zend.db.table.update.example">
604 <title>Example of updating rows in a Table</title>
606 <programlisting language="php"><![CDATA[
610 'updated_on' => '2007-03-23',
611 'bug_status' => 'FIXED'
614 $where = $table->getAdapter()->quoteInto('bug_id = ?', 1234);
616 $table->update($data, $where);
621 Since the table <methodname>update()</methodname> method proxies to the database adapter
622 <link linkend="zend.db.adapter.write.update"><methodname>update()</methodname></link>
623 method, the second argument can be an array of <acronym>SQL</acronym> expressions. The
624 expressions are combined as Boolean terms using an <constant>AND</constant> operator.
629 The values and identifiers in the <acronym>SQL</acronym> expression are not quoted
630 for you. If you have values or identifiers that require quoting, you are responsible
631 for doing this. Use the <methodname>quote()</methodname>,
632 <methodname>quoteInto()</methodname>, and <methodname>quoteIdentifier()</methodname>
633 methods of the database adapter.
638 <sect2 id="zend.db.table.delete">
639 <title>Deleting Rows from a Table</title>
642 You can delete rows from a database table using the <methodname>delete()</methodname>
643 method. This method takes one argument, which is an <acronym>SQL</acronym> expression
644 that is used in a <constant>WHERE</constant> clause, as criteria for the rows to delete.
647 <example id="zend.db.table.delete.example">
648 <title>Example of deleting rows from a Table</title>
650 <programlisting language="php"><![CDATA[
653 $where = $table->getAdapter()->quoteInto('bug_id = ?', 1235);
655 $table->delete($where);
660 Since the table <methodname>delete()</methodname> method proxies to the database adapter
661 <link linkend="zend.db.adapter.write.delete"><methodname>delete()</methodname></link>
662 method, the argument can also be an array of <acronym>SQL</acronym> expressions. The
663 expressions are combined as Boolean terms using an <constant>AND</constant> operator.
668 The values and identifiers in the <acronym>SQL</acronym> expression are not quoted
669 for you. If you have values or identifiers that require quoting, you are responsible
670 for doing this. Use the <methodname>quote()</methodname>,
671 <methodname>quoteInto()</methodname>, and <methodname>quoteIdentifier()</methodname>
672 methods of the database adapter.
677 <sect2 id="zend.db.table.find">
678 <title>Finding Rows by Primary Key</title>
681 You can query the database table for rows matching specific values in the primary key,
682 using the <methodname>find()</methodname> method. The first argument of this method is
683 either a single value or an array of values to match against the primary key of the
687 <example id="zend.db.table.find.example">
688 <title>Example of finding rows by primary key values</title>
690 <programlisting language="php"><![CDATA[
695 $rows = $table->find(1234);
697 // Find multiple rows
698 // Also returns a Rowset
699 $rows = $table->find(array(1234, 5678));
704 If you specify a single value, the method returns at most one row, because a primary
705 key cannot have duplicate values and there is at most one row in the database table
706 matching the value you specify. If you specify multiple values in an array, the method
707 returns at most as many rows as the number of distinct values you specify.
711 The <methodname>find()</methodname> method might return fewer rows than the number of
712 values you specify for the primary key, if some of the values don't match any rows in
713 the database table. The method even may return zero rows. Because the number of rows
714 returned is variable, the <methodname>find()</methodname> method returns an object of
715 type <classname>Zend_Db_Table_Rowset_Abstract</classname>.
719 If the primary key is a compound key, that is, it consists of multiple columns, you can
720 specify the additional columns as additional arguments to the
721 <methodname>find()</methodname> method. You must provide as many arguments as the number
722 of columns in the table's primary key.
726 To find multiple rows from a table with a compound primary key, provide an array for
727 each of the arguments. All of these arrays must have the same number of elements. The
728 values in each array are formed into tuples in order; for example, the first element
729 in all the array arguments define the first compound primary key value, then the second
730 elements of all the arrays define the second compound primary key value, and so on.
733 <example id="zend.db.table.find.example-compound">
734 <title>Example of finding rows by compound primary key values</title>
737 The call to <methodname>find()</methodname> below to match multiple rows can match
738 two rows in the database. The first row must have primary key value (1234, 'ABC'),
739 and the second row must have primary key value (5678, 'DEF').
742 <programlisting language="php"><![CDATA[
743 class BugsProducts extends Zend_Db_Table_Abstract
745 protected $_name = 'bugs_products';
746 protected $_primary = array('bug_id', 'product_id');
749 $table = new BugsProducts();
751 // Find a single row with a compound primary key
753 $rows = $table->find(1234, 'ABC');
755 // Find multiple rows with compound primary keys
756 // Also returns a Rowset
757 $rows = $table->find(array(1234, 5678), array('ABC', 'DEF'));
762 <sect2 id="zend.db.table.fetch-all">
763 <title>Querying for a Set of Rows</title>
765 <sect3 id="zend.db.table.fetch-all.select">
766 <title>Select API</title>
770 The <acronym>API</acronym> for fetch operations has been superseded to allow
771 a <classname>Zend_Db_Table_Select</classname> object to modify the query.
772 However, the deprecated usage of the <methodname>fetchRow()</methodname> and
773 <methodname>fetchAll()</methodname> methods will continue to work without
778 The following statements are all legal and functionally identical, however
779 it is recommended to update your code to take advantage of the new usage
783 <programlisting language="php"><![CDATA[
787 $rows = $table->fetchAll(
788 'bug_status = "NEW"',
793 $rows = $table->fetchAll(
795 ->where('bug_status = ?', 'NEW')
796 ->order('bug_id ASC')
800 $rows = $table->fetchAll(
802 ->where('bug_status = :status')
803 ->bind(array(':status'=>'NEW')
804 ->order('bug_id ASC')
809 * Fetching a single row
811 $row = $table->fetchRow(
812 'bug_status = "NEW"',
815 $row = $table->fetchRow(
817 ->where('bug_status = ?', 'NEW')
818 ->order('bug_id ASC')
821 $row = $table->fetchRow(
823 ->where('bug_status = :status')
824 ->bind(array(':status'=>'NEW')
825 ->order('bug_id ASC')
831 The <classname>Zend_Db_Table_Select</classname> object is an extension of the
832 <classname>Zend_Db_Select</classname> object that applies specific restrictions to
833 a query. The enhancements and restrictions are:
839 You <emphasis>can</emphasis> elect to return a subset of columns within a
840 fetchRow or fetchAll query. This can provide optimization benefits where
841 returning a large set of results for all columns is not desirable.
847 You <emphasis>can</emphasis> specify columns that evaluate expressions from
848 within the selected table. However this will mean that the returned row or
849 rowset will be <property>readOnly</property> and cannot be used for
850 <methodname>save()</methodname> operations. A
851 <classname>Zend_Db_Table_Row</classname> with
852 <property>readOnly</property> status will throw an exception if a
853 <methodname>save()</methodname> operation is attempted.
859 You <emphasis>can</emphasis> allow <constant>JOIN</constant> clauses on a
860 select to allow multi-table lookups.
866 You <emphasis>can not</emphasis> specify columns from a JOINed tabled to be
867 returned in a row or rowset. Doing so will trigger a <acronym>PHP</acronym>
868 error. This was done to ensure the integrity of the
869 <classname>Zend_Db_Table</classname> is retained. i.e. A
870 <classname>Zend_Db_Table_Row</classname> should only reference columns
871 derived from its parent table.
876 <example id="zend.db.table.qry.rows.set.simple.usage.example">
877 <title>Simple usage</title>
879 <programlisting language="php"><![CDATA[
882 $select = $table->select();
883 $select->where('bug_status = ?', 'NEW');
885 $rows = $table->fetchAll($select);
890 Fluent interfaces are implemented across the component, so this can be rewritten
891 this in a more abbreviated form.
894 <example id="zend.db.table.qry.rows.set.fluent.interface.example">
895 <title>Example of fluent interface</title>
897 <programlisting language="php"><![CDATA[
901 $table->fetchAll($table->select()->where('bug_status = ?', 'NEW'));
906 <sect3 id="zend.db.table.fetch-all.usage">
907 <title>Fetching a rowset</title>
910 You can query for a set of rows using any criteria other than the primary key
911 values, using the <methodname>fetchAll()</methodname> method of the Table class.
912 This method returns an object of type
913 <classname>Zend_Db_Table_Rowset_Abstract</classname>.
916 <example id="zend.db.table.qry.rows.set.finding.row.example">
917 <title>Example of finding rows by an expression</title>
919 <programlisting language="php"><![CDATA[
922 $select = $table->select()->where('bug_status = ?', 'NEW');
924 $rows = $table->fetchAll($select);
929 You may also pass sorting criteria in an <constant>ORDER</constant> BY clause, as
930 well as count and offset integer values, used to make the query return a specific
931 subset of rows. These values are used in a <constant>LIMIT</constant> clause, or in
932 equivalent logic for <acronym>RDBMS</acronym> brands that do not support the
933 <constant>LIMIT</constant> syntax.
936 <example id="zend.db.table.fetch-all.example2">
937 <title>Example of finding rows by an expression</title>
939 <programlisting language="php"><![CDATA[
944 // Return the 21st through 30th rows
948 $select = $table->select()->where('bug_status = ?', 'NEW')
950 ->limit($count, $offset);
952 $rows = $table->fetchAll($select);
957 All of the arguments above are optional. If you omit the <constant>ORDER</constant>
958 clause, the result set includes rows from the table in an unpredictable order. If
959 no <constant>LIMIT</constant> clause is set, you retrieve every row in the table
960 that matches the <constant>WHERE</constant> clause.
964 <sect3 id="zend.db.table.advanced.usage">
965 <title>Advanced usage</title>
968 For more specific and optimized requests, you may wish to limit the number of
969 columns returned in a row or rowset. This can be achieved by passing a
970 <constant>FROM</constant> clause to the select object. The first argument in the
971 <constant>FROM</constant> clause is identical to that of a
972 <classname>Zend_Db_Select</classname> object with the addition of being able to pass
973 an instance of <classname>Zend_Db_Table_Abstract</classname> and have it
974 automatically determine the table name.
977 <example id="zend.db.table.qry.rows.set.retrieving.a.example">
978 <title>Retrieving specific columns</title>
980 <programlisting language="php"><![CDATA[
983 $select = $table->select();
984 $select->from($table, array('bug_id', 'bug_description'))
985 ->where('bug_status = ?', 'NEW');
987 $rows = $table->fetchAll($select);
993 The rowset contains rows that are still 'valid' - they simply contain a
994 subset of the columns of a table. If a <methodname>save()</methodname>
995 method is called on a partial row then only the fields available will be
1001 You can also specify expressions within a <constant>FROM</constant> clause and have
1002 these returned as a readOnly row or rowset. In this example we will return a rows
1003 from the bugs table that show an aggregate of the number of new bugs reported by
1004 individuals. Note the <constant>GROUP</constant> clause. The 'count' column will be
1005 made available to the row for evaluation and can be accessed as if it were part of
1009 <example id="zend.db.table.qry.rows.set.retrieving.b.example">
1010 <title>Retrieving expressions as columns</title>
1012 <programlisting language="php"><![CDATA[
1013 $table = new Bugs();
1015 $select = $table->select();
1016 $select->from($table,
1017 array('COUNT(reported_by) as `count`', 'reported_by'))
1018 ->where('bug_status = ?', 'NEW')
1019 ->group('reported_by');
1021 $rows = $table->fetchAll($select);
1022 ]]></programlisting>
1026 You can also use a lookup as part of your query to further refine your fetch
1027 operations. In this example the accounts table is queried as part of a search for
1028 all new bugs reported by 'Bob'.
1031 <example id="zend.db.table.qry.rows.set.refine.example">
1032 <title>Using a lookup table to refine the results of fetchAll()</title>
1034 <programlisting language="php"><![CDATA[
1035 $table = new Bugs();
1037 // retrieve with from part set, important when joining
1038 $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
1039 $select->setIntegrityCheck(false)
1040 ->where('bug_status = ?', 'NEW')
1041 ->join('accounts', 'accounts.account_name = bugs.reported_by')
1042 ->where('accounts.account_name = ?', 'Bob');
1044 $rows = $table->fetchAll($select);
1045 ]]></programlisting>
1049 The <classname>Zend_Db_Table_Select</classname> is primarily used to constrain and
1050 validate so that it may enforce the criteria for a legal <constant>SELECT</constant>
1051 query. However there may be certain cases where you require the flexibility of the
1052 <classname>Zend_Db_Table_Row</classname> component and do not require a writable or
1053 deletable row. for this specific user case, it is possible to retrieve a row or
1054 rowset by passing a <constant>FALSE</constant> value to
1055 <methodname>setIntegrityCheck()</methodname>. The resulting row or rowset will be
1056 returned as a 'locked' row (meaning the <methodname>save()</methodname>,
1057 <methodname>delete()</methodname> and any field-setting methods will throw an
1061 <example id="zend.db.table.qry.rows.set.integrity.example">
1063 Removing the integrity check on Zend_Db_Table_Select to allow JOINed rows
1066 <programlisting language="php"><![CDATA[
1067 $table = new Bugs();
1069 $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
1070 ->setIntegrityCheck(false);
1071 $select->where('bug_status = ?', 'NEW')
1073 'accounts.account_name = bugs.reported_by',
1075 ->where('accounts.account_name = ?', 'Bob');
1077 $rows = $table->fetchAll($select);
1078 ]]></programlisting>
1083 <sect2 id="zend.db.table.fetch-row">
1084 <title>Querying for a Single Row</title>
1087 You can query for a single row using criteria similar to that of the
1088 <methodname>fetchAll()</methodname> method.
1091 <example id="zend.db.table.fetch-row.example1">
1092 <title>Example of finding a single row by an expression</title>
1094 <programlisting language="php"><![CDATA[
1095 $table = new Bugs();
1097 $select = $table->select()->where('bug_status = ?', 'NEW')
1100 $row = $table->fetchRow($select);
1101 ]]></programlisting>
1105 This method returns an object of type <classname>Zend_Db_Table_Row_Abstract</classname>.
1106 If the search criteria you specified match no rows in the database table, then
1107 <methodname>fetchRow()</methodname> returns <acronym>PHP</acronym>'s
1108 <constant>NULL</constant> value.
1112 <sect2 id="zend.db.table.info">
1113 <title>Retrieving Table Metadata Information</title>
1116 The <classname>Zend_Db_Table_Abstract</classname> class provides some information about
1117 its metadata. The <methodname>info()</methodname> method returns an array structure with
1118 information about the table, its columns and primary key, and other metadata.
1121 <example id="zend.db.table.info.example">
1122 <title>Example of getting the table name</title>
1124 <programlisting language="php"><![CDATA[
1125 $table = new Bugs();
1127 $info = $table->info();
1129 echo "The table name is " . $info['name'] . "\n";
1130 ]]></programlisting>
1134 The keys of the array returned by the <methodname>info()</methodname> method are
1141 <emphasis>name</emphasis> => the name of the table.
1147 <emphasis>cols</emphasis> => an array, naming the columns of
1154 <emphasis>primary</emphasis> => an array, naming the columns in
1161 <emphasis>metadata</emphasis> => an associative array, mapping
1162 column names to information about the columns. This is the information returned
1163 by the <methodname>describeTable()</methodname> method.
1169 <emphasis>rowClass</emphasis> => the name of the concrete class
1170 used for Row objects returned by methods of this table instance. This defaults
1171 to <classname>Zend_Db_Table_Row</classname>.
1177 <emphasis>rowsetClass</emphasis> => the name of the concrete
1178 class used for Rowset objects returned by methods of this table instance. This
1179 defaults to <classname>Zend_Db_Table_Rowset</classname>.
1185 <emphasis>referenceMap</emphasis> => an associative array, with
1186 information about references from this table to any parent tables. See
1187 <link linkend="zend.db.table.relationships.defining">this chapter</link>.
1193 <emphasis>dependentTables</emphasis> => an array of class names
1194 of tables that reference this table. See
1195 <link linkend="zend.db.table.relationships.defining">this chapter</link>.
1201 <emphasis>schema</emphasis> => the name of the schema (or
1202 database or tablespace) for this table.
1208 <sect2 id="zend.db.table.metadata.caching">
1209 <title>Caching Table Metadata</title>
1212 By default, <classname>Zend_Db_Table_Abstract</classname> queries the
1213 underlying database for <link linkend="zend.db.table.info">table
1214 metadata</link> whenever that data is needed to perform table
1215 operations. The table object fetches the table metadata from the
1216 database using the adapter's <methodname>describeTable()</methodname> method.
1217 Operations requiring this introspection include:
1221 <listitem><para><methodname>insert()</methodname></para></listitem>
1222 <listitem><para><methodname>find()</methodname></para></listitem>
1223 <listitem><para><methodname>info()</methodname></para></listitem>
1227 In some circumstances, particularly when many table objects are instantiated against
1228 the same database table, querying the database for the table metadata for each instance
1229 may be undesirable from a performance standpoint. In such cases, users may benefit by
1230 caching the table metadata retrieved from the database.
1234 There are two primary ways in which a user may take advantage of table metadata
1242 <methodname>Zend_Db_Table_Abstract::setDefaultMetadataCache()</methodname></emphasis>
1243 - This allows a developer to once set the default cache object to be used
1244 for all table classes.
1251 <methodname>Zend_Db_Table_Abstract::__construct()</methodname></emphasis> -
1252 This allows a developer to set the cache object to be used for a particular
1253 table class instance.
1259 In both cases, the cache specification must be either <constant>NULL</constant> (i.e.,
1260 no cache used) or an instance of
1261 <link linkend="zend.cache.frontends.core"><classname>Zend_Cache_Core</classname></link>.
1262 The methods may be used in conjunction when it is desirable to have both a default
1263 metadata cache and the ability to change the cache for individual table objects.
1266 <example id="zend.db.table.metadata.caching-default">
1267 <title>Using a Default Metadata Cache for all Table Objects</title>
1270 The following code demonstrates how to set a default metadata cache to be used for
1274 <programlisting language="php"><![CDATA[
1275 // First, set up the Cache
1276 $frontendOptions = array(
1277 'automatic_serialization' => true
1280 $backendOptions = array(
1281 'cache_dir' => 'cacheDir'
1284 $cache = Zend_Cache::factory('Core',
1289 // Next, set the cache to be used with all table objects
1290 Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
1292 // A table class is also needed
1293 class Bugs extends Zend_Db_Table_Abstract
1298 // Each instance of Bugs now uses the default metadata cache
1300 ]]></programlisting>
1303 <example id="zend.db.table.metadata.caching-instance">
1304 <title>Using a Metadata Cache for a Specific Table Object</title>
1307 The following code demonstrates how to set a metadata cache for a specific table
1311 <programlisting language="php"><![CDATA[
1312 // First, set up the Cache
1313 $frontendOptions = array(
1314 'automatic_serialization' => true
1317 $backendOptions = array(
1318 'cache_dir' => 'cacheDir'
1321 $cache = Zend_Cache::factory('Core',
1326 // A table class is also needed
1327 class Bugs extends Zend_Db_Table_Abstract
1332 // Configure an instance upon instantiation
1333 $bugs = new Bugs(array('metadataCache' => $cache));
1334 ]]></programlisting>
1338 <title>Automatic Serialization with the Cache Frontend</title>
1341 Since the information returned from the adapter's
1342 <methodname>describeTable()</methodname> method is an array, ensure that the
1343 <property>automatic_serialization</property> option is set to
1344 <constant>TRUE</constant> for the <classname>Zend_Cache_Core</classname> frontend.
1349 Though the above examples use <classname>Zend_Cache_Backend_File</classname>, developers
1350 may use whatever cache backend is appropriate for the situation. Please see
1351 <link linkend="zend.cache">Zend_Cache</link> for more information.
1354 <sect3 id="zend.db.table.metadata.caching.hardcoding">
1355 <title>Hardcoding Table Metadata</title>
1358 To take metadata caching a step further, you can also choose to
1359 hardcode metadata. In this particular case, however, any changes
1360 to the table schema will require a change in your code. As such,
1361 it is only recommended for those who are optimizing for
1366 The metadata structure is as follows:
1369 <programlisting language="php"><![CDATA[
1370 protected $_metadata = array(
1371 '<column_name>' => array(
1372 'SCHEMA_NAME' => <string>,
1373 'TABLE_NAME' => <string>,
1374 'COLUMN_NAME' => <string>,
1375 'COLUMN_POSITION' => <int>,
1376 'DATA_TYPE' => <string>,
1377 'DEFAULT' => NULL|<value>,
1378 'NULLABLE' => <bool>,
1379 'LENGTH' => <string - length>,
1380 'SCALE' => NULL|<value>,
1381 'PRECISION' => NULL|<value>,
1382 'UNSIGNED' => NULL|<bool>,
1383 'PRIMARY' => <bool>,
1384 'PRIMARY_POSITION' => <int>,
1385 'IDENTITY' => <bool>,
1387 // additional columns...
1389 ]]></programlisting>
1392 An easy way to get the appropriate values is to use the metadata
1393 cache, and then to deserialize values stored in the cache.
1397 You can disable this optimization by turning of the
1398 <property>metadataCacheInClass</property> flag:
1401 <programlisting language="php"><![CDATA[
1402 // At instantiation:
1403 $bugs = new Bugs(array('metadataCacheInClass' => false));
1406 $bugs->setMetadataCacheInClass(false);
1407 ]]></programlisting>
1410 The flag is enabled by default, which ensures that the
1411 <varname>$_metadata</varname> array is only populated once per
1417 <sect2 id="zend.db.table.extending">
1418 <title>Customizing and Extending a Table Class</title>
1420 <sect3 id="zend.db.table.extending.row-rowset">
1421 <title>Using Custom Row or Rowset Classes</title>
1424 By default, methods of the Table class return a Rowset in instances of the concrete
1425 class <classname>Zend_Db_Table_Rowset</classname>, and Rowsets contain a collection
1426 of instances of the concrete class <classname>Zend_Db_Table_Row</classname> You can
1427 specify an alternative class to use for either of these, but they must be classes
1428 that extend <classname>Zend_Db_Table_Rowset_Abstract</classname> and
1429 <classname>Zend_Db_Table_Row_Abstract</classname>, respectively.
1433 You can specify Row and Rowset classes using the Table constructor's options array,
1434 in keys '<property>rowClass</property>' and '<property>rowsetClass</property>'
1435 respectively. Specify the names of the classes using strings.
1438 <example id="zend.db.table.extending.row-rowset.example">
1439 <title>Example of specifying the Row and Rowset classes</title>
1441 <programlisting language="php"><![CDATA[
1442 class My_Row extends Zend_Db_Table_Row_Abstract
1447 class My_Rowset extends Zend_Db_Table_Rowset_Abstract
1454 'rowClass' => 'My_Row',
1455 'rowsetClass' => 'My_Rowset'
1459 $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
1461 // Returns an object of type My_Rowset,
1462 // containing an array of objects of type My_Row.
1463 $rows = $table->fetchAll($where);
1464 ]]></programlisting>
1468 You can change the classes by specifying them with the
1469 <methodname>setRowClass()</methodname> and <methodname>setRowsetClass()</methodname>
1470 methods. This applies to rows and rowsets created subsequently; it does not change
1471 the class of any row or rowset objects you have created previously.
1474 <example id="zend.db.table.extending.row-rowset.example2">
1475 <title>Example of changing the Row and Rowset classes</title>
1477 <programlisting language="php"><![CDATA[
1478 $table = new Bugs();
1480 $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
1482 // Returns an object of type Zend_Db_Table_Rowset
1483 // containing an array of objects of type Zend_Db_Table_Row.
1484 $rowsStandard = $table->fetchAll($where);
1486 $table->setRowClass('My_Row');
1487 $table->setRowsetClass('My_Rowset');
1489 // Returns an object of type My_Rowset,
1490 // containing an array of objects of type My_Row.
1491 $rowsCustom = $table->fetchAll($where);
1493 // The $rowsStandard object still exists, and it is unchanged.
1494 ]]></programlisting>
1498 For more information on the Row and Rowset classes, see
1499 <link linkend="zend.db.table.row">this chapter</link> and <link
1500 linkend="zend.db.table.rowset">this one</link>.
1504 <sect3 id="zend.db.table.extending.insert-update">
1505 <title>Defining Custom Logic for Insert, Update, and Delete</title>
1508 You can override the <methodname>insert()</methodname> and
1509 <methodname>update()</methodname> methods in your Table class. This gives you the
1510 opportunity to implement custom code that is executed before performing the database
1511 operation. Be sure to call the parent class method when you are done.
1514 <example id="zend.db.table.extending.insert-update.example">
1515 <title>Custom logic to manage timestamps</title>
1517 <programlisting language="php"><![CDATA[
1518 class Bugs extends Zend_Db_Table_Abstract
1520 protected $_name = 'bugs';
1522 public function insert(array $data)
1525 if (empty($data['created_on'])) {
1526 $data['created_on'] = time();
1528 return parent::insert($data);
1531 public function update(array $data, $where)
1534 if (empty($data['updated_on'])) {
1535 $data['updated_on'] = time();
1537 return parent::update($data, $where);
1540 ]]></programlisting>
1544 You can also override the <methodname>delete()</methodname> method.
1548 <sect3 id="zend.db.table.extending.finders">
1549 <title>Define Custom Search Methods in Zend_Db_Table</title>
1552 You can implement custom query methods in your Table class, if you have frequent
1553 need to do queries against this table with specific criteria. Most queries can be
1554 written using <methodname>fetchAll()</methodname>, but this requires that you
1555 duplicate code to form the query conditions if you need to run the query in several
1556 places in your application. Therefore it can be convenient to implement a method in
1557 the Table class to perform frequently-used queries against this table.
1560 <example id="zend.db.table.extending.finders.example">
1561 <title>Custom method to find bugs by status</title>
1563 <programlisting language="php"><![CDATA[
1564 class Bugs extends Zend_Db_Table_Abstract
1566 protected $_name = 'bugs';
1568 public function findByStatus($status)
1570 $where = $this->getAdapter()->quoteInto('bug_status = ?', $status);
1571 return $this->fetchAll($where, 'bug_id');
1574 ]]></programlisting>
1578 <sect3 id="zend.db.table.extending.inflection">
1579 <title>Define Inflection in Zend_Db_Table</title>
1582 Some people prefer that the table class name match a table name in the
1583 <acronym>RDBMS</acronym> by using a string transformation called
1584 <emphasis>inflection</emphasis>.
1588 For example, if your table class name is "BugsProducts", it would
1589 match the physical table in the database called "bugs_products", if
1590 you omit the explicit declaration of the <varname>$_name</varname> class property.
1591 In this inflection mapping, the class name spelled in "CamelCase" format would be
1592 transformed to lower case, and words are separated with an underscore.
1596 You can specify the database table name independently from the class name by
1597 declaring the table name with the <varname>$_name</varname> class property in each
1598 of your table classes.
1602 <classname>Zend_Db_Table_Abstract</classname> performs no inflection to map the
1603 class name to the table name. If you omit the declaration of
1604 <varname>$_name</varname> in your table class, the class maps to a database table
1605 that matches the spelling of the class name exactly.
1609 It is inappropriate to transform identifiers from the database, because this can
1610 lead to ambiguity or make some identifiers inaccessible. Using the
1611 <acronym>SQL</acronym> identifiers exactly as they appear in the database makes
1612 <classname>Zend_Db_Table_Abstract</classname> both simpler and more flexible.
1616 If you prefer to use inflection, then you must implement the transformation
1617 yourself, by overriding the <methodname>_setupTableName()</methodname> method in
1618 your Table classes. One way to do this is to define an abstract class that extends
1619 <classname>Zend_Db_Table_Abstract</classname>, and then the rest of your tables
1620 extend your new abstract class.
1623 <example id="zend.db.table.extending.inflection.example">
1624 <title>Example of an abstract table class that implements inflection</title>
1626 <programlisting language="php"><![CDATA[
1627 abstract class MyAbstractTable extends Zend_Db_Table_Abstract
1629 protected function _setupTableName()
1631 if (!$this->_name) {
1632 $this->_name = myCustomInflector(get_class($this));
1634 parent::_setupTableName();
1638 class BugsProducts extends MyAbstractTable
1641 ]]></programlisting>
1645 You are responsible for writing the functions to perform inflection transformation.
1646 Zend Framework does not provide such a function.
1652 vim:se ts=4 sw=4 et: