2
0

Zend_Db_Table.xml 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.db.table">
  4. <title>Zend_Db_Table</title>
  5. <sect2 id="zend.db.table.introduction">
  6. <title>Introduction</title>
  7. <para>
  8. The <classname>Zend_Db_Table</classname> class is an object-oriented interface to
  9. database tables. It provides methods for many common operations on tables. The base
  10. class is extensible, so you can add custom logic.
  11. </para>
  12. <para>
  13. The <classname>Zend_Db_Table</classname> solution is an implementation of the
  14. <ulink url="http://www.martinfowler.com/eaaCatalog/tableDataGateway.html">Table Data
  15. Gateway</ulink> pattern. The solution also includes a class that implements the
  16. <ulink url="http://www.martinfowler.com/eaaCatalog/rowDataGateway.html">Row Data
  17. Gateway</ulink> pattern.
  18. </para>
  19. </sect2>
  20. <sect2 id="zend.db.table.concrete">
  21. <title>Using Zend_Db_Table as a concrete class</title>
  22. <para>
  23. As of Zend Framework 1.9, you can instantiate <classname>Zend_Db_Table</classname>. This
  24. added benefit is that you do not have to extend a base class and configure it to do
  25. simple operations such as selecting, inserting, updating and deleteing on a single
  26. table. below is an example of the simplest of use cases.
  27. </para>
  28. <example id="zend.db.table.defining.concrete-instantiation.example1">
  29. <title>Declaring a table class with just the string name</title>
  30. <programlisting language="php"><![CDATA[
  31. Zend_Db_Table::setDefaultAdapter($dbAdapter);
  32. $bugTable = new Zend_Db_Table('bug');
  33. ]]></programlisting>
  34. </example>
  35. <para>
  36. The above example represents the simplest of use cases. Make not of all the
  37. options describe below for configuring <classname>Zend_Db_Table</classname> tables. If
  38. you want to be able to use the concrete usage case, in addition to the more complex
  39. relationhip features, see the <classname>Zend_Db_Table_Definition</classname>
  40. documentation.
  41. </para>
  42. </sect2>
  43. <sect2 id="zend.db.table.defining">
  44. <title>Defining a Table Class</title>
  45. <para>
  46. For each table in your database that you want to access, define a class that extends
  47. <classname>Zend_Db_Table_Abstract</classname>.
  48. </para>
  49. <sect3 id="zend.db.table.defining.table-schema">
  50. <title>Defining the Table Name and Schema</title>
  51. <para>
  52. Declare the database table for which this class is defined, using the protected
  53. variable <varname>$_name</varname>. This is a string, and must contain the name of
  54. the table spelled as it appears in the database.
  55. </para>
  56. <example id="zend.db.table.defining.table-schema.example1">
  57. <title>Declaring a table class with explicit table name</title>
  58. <programlisting language="php"><![CDATA[
  59. class Bugs extends Zend_Db_Table_Abstract
  60. {
  61. protected $_name = 'bugs';
  62. }
  63. ]]></programlisting>
  64. </example>
  65. <para>
  66. If you don't specify the table name, it defaults to the name of the class. If you
  67. rely on this default, the class name must match the spelling of the table name as
  68. it appears in the database.
  69. </para>
  70. <example id="zend.db.table.defining.table-schema.example">
  71. <title>Declaring a table class with implicit table name</title>
  72. <programlisting language="php"><![CDATA[
  73. class bugs extends Zend_Db_Table_Abstract
  74. {
  75. // table name matches class name
  76. }
  77. ]]></programlisting>
  78. </example>
  79. <para>
  80. You can also declare the schema for the table, either with the protected variable
  81. <varname>$_schema</varname>, or with the schema prepended to the table name in the
  82. <varname>$_name</varname> property. Any schema specified with the
  83. <varname>$_name</varname> property takes precedence over a schema specified with the
  84. <varname>$_schema</varname> property. In some <acronym>RDBMS</acronym> brands, the
  85. term for schema is "database" or "tablespace," but it is used similarly.
  86. </para>
  87. <example id="zend.db.table.defining.table-schema.example3">
  88. <title>Declaring a table class with schema</title>
  89. <programlisting language="php"><![CDATA[
  90. // First alternative:
  91. class Bugs extends Zend_Db_Table_Abstract
  92. {
  93. protected $_schema = 'bug_db';
  94. protected $_name = 'bugs';
  95. }
  96. // Second alternative:
  97. class Bugs extends Zend_Db_Table_Abstract
  98. {
  99. protected $_name = 'bug_db.bugs';
  100. }
  101. // If schemas are specified in both $_name and $_schema, the one
  102. // specified in $_name takes precedence:
  103. class Bugs extends Zend_Db_Table_Abstract
  104. {
  105. protected $_name = 'bug_db.bugs';
  106. protected $_schema = 'ignored';
  107. }
  108. ]]></programlisting>
  109. </example>
  110. <para>
  111. The schema and table names may also be specified via constructor configuration
  112. directives, which override any default values specified with the
  113. <varname>$_name</varname> and <varname>$_schema</varname> properties. A schema
  114. specification given with the <property>name</property> directive overrides any value
  115. provided with the <property>schema</property> option.
  116. </para>
  117. <example id="zend.db.table.defining.table-schema.example.constructor">
  118. <title>Declaring table and schema names upon instantiation</title>
  119. <programlisting language="php"><![CDATA[
  120. class Bugs extends Zend_Db_Table_Abstract
  121. {
  122. }
  123. // First alternative:
  124. $tableBugs = new Bugs(array('name' => 'bugs', 'schema' => 'bug_db'));
  125. // Second alternative:
  126. $tableBugs = new Bugs(array('name' => 'bug_db.bugs'));
  127. // If schemas are specified in both 'name' and 'schema', the one
  128. // specified in 'name' takes precedence:
  129. $tableBugs = new Bugs(array('name' => 'bug_db.bugs',
  130. 'schema' => 'ignored'));
  131. ]]></programlisting>
  132. </example>
  133. <para>
  134. If you don't specify the schema name, it defaults to the schema to which your
  135. database adapter instance is connected.
  136. </para>
  137. </sect3>
  138. <sect3 id="zend.db.table.defining.primary-key">
  139. <title>Defining the Table Primary Key</title>
  140. <para>
  141. Every table must have a primary key. You can declare the column for the primary key
  142. using the protected variable <varname>$_primary</varname>. This is either a string
  143. that names the single column for the primary key, or else it is an array of column
  144. names if your primary key is a compound key.
  145. </para>
  146. <example id="zend.db.table.defining.primary-key.example">
  147. <title>Example of specifying the primary key</title>
  148. <programlisting language="php"><![CDATA[
  149. class Bugs extends Zend_Db_Table_Abstract
  150. {
  151. protected $_name = 'bugs';
  152. protected $_primary = 'bug_id';
  153. }
  154. ]]></programlisting>
  155. </example>
  156. <para>
  157. If you don't specify the primary key, <classname>Zend_Db_Table_Abstract</classname>
  158. tries to discover the primary key based on the information provided by the
  159. <methodname>describeTable()</methodname>´ method.
  160. </para>
  161. <note>
  162. <para>
  163. Every table class must know which columns can be used to address rows
  164. uniquely. If no primary key columns are specified in the table class
  165. definition or the table constructor arguments, or discovered in the table
  166. metadata provided by <methodname>describeTable()</methodname>, then the table
  167. cannot be used with <classname>Zend_Db_Table</classname>.
  168. </para>
  169. </note>
  170. </sect3>
  171. <sect3 id="zend.db.table.defining.setup">
  172. <title>Overriding Table Setup Methods</title>
  173. <para>
  174. When you create an instance of a Table class, the constructor calls a set of
  175. protected methods that initialize metadata for the table. You can extend any of
  176. these methods to define metadata explicitly. Remember to call the method of the
  177. same name in the parent class at the end of your method.
  178. </para>
  179. <example id="zend.db.table.defining.setup.example">
  180. <title>Example of overriding the _setupTableName() method</title>
  181. <programlisting language="php"><![CDATA[
  182. class Bugs extends Zend_Db_Table_Abstract
  183. {
  184. protected function _setupTableName()
  185. {
  186. $this->_name = 'bugs';
  187. parent::_setupTableName();
  188. }
  189. }
  190. ]]></programlisting>
  191. </example>
  192. <para>
  193. The setup methods you can override are the following:
  194. </para>
  195. <itemizedlist>
  196. <listitem>
  197. <para>
  198. <methodname>_setupDatabaseAdapter()</methodname> checks that an adapter has
  199. been provided; gets a default adapter from the registry if needed. By
  200. overriding this method, you can set a database adapter from some other
  201. source.
  202. </para>
  203. </listitem>
  204. <listitem>
  205. <para>
  206. <methodname>_setupTableName()</methodname> defaults the table name to the
  207. name of the class. By overriding this method, you can set the table name
  208. before this default behavior runs.
  209. </para>
  210. </listitem>
  211. <listitem>
  212. <para>
  213. <methodname>_setupMetadata()</methodname> sets the schema if the table name
  214. contains the pattern "<command>schema.table</command>"; calls
  215. <methodname>describeTable()</methodname> to get metadata information;
  216. defaults the <varname>$_cols</varname> array to the columns reported by
  217. <methodname>describeTable()</methodname>. By overriding this method, you can
  218. specify the columns.
  219. </para>
  220. </listitem>
  221. <listitem>
  222. <para>
  223. <methodname>_setupPrimaryKey()</methodname> defaults the primary key columns
  224. to those reported by <methodname>describeTable()</methodname>; checks that
  225. the primary key columns are included in the <varname>$_cols</varname> array.
  226. By overriding this method, you can specify the primary key columns.
  227. </para>
  228. </listitem>
  229. </itemizedlist>
  230. </sect3>
  231. <sect3 id="zend.db.table.initialization">
  232. <title>Table initialization</title>
  233. <para>
  234. If application-specific logic needs to be initialized when a Table class is
  235. constructed, you can select to move your tasks to the
  236. <methodname>init()</methodname> method, which is called after all Table metadata has
  237. been processed. This is recommended over the <methodname>__construct()</methodname>
  238. method if you do not need to alter the metadata in any programmatic way.
  239. </para>
  240. <example id="zend.db.table.defining.init.usage.example">
  241. <title>Example usage of init() method</title>
  242. <programlisting language="php"><![CDATA[
  243. class Bugs extends Zend_Db_Table_Abstract
  244. {
  245. protected $_observer;
  246. public function init()
  247. {
  248. $this->_observer = new MyObserverClass();
  249. }
  250. }
  251. ]]></programlisting>
  252. </example>
  253. </sect3>
  254. </sect2>
  255. <sect2 id="zend.db.table.constructing">
  256. <title>Creating an Instance of a Table</title>
  257. <para>
  258. Before you use a Table class, create an instance using its constructor. The
  259. constructor's argument is an array of options. The most important option to a Table
  260. constructor is the database adapter instance, representing a live connection to an
  261. <acronym>RDBMS</acronym>. There are three ways of specifying the database adapter to a
  262. Table class, and these three ways are described below:
  263. </para>
  264. <sect3 id="zend.db.table.constructing.adapter">
  265. <title>Specifying a Database Adapter</title>
  266. <para>
  267. The first way to provide a database adapter to a Table class is by passing it as an
  268. object of type <classname>Zend_Db_Adapter_Abstract</classname> in the options array,
  269. identified by the key '<property>db</property>'.
  270. </para>
  271. <example id="zend.db.table.constructing.adapter.example">
  272. <title>Example of constructing a Table using an Adapter object</title>
  273. <programlisting language="php"><![CDATA[
  274. $db = Zend_Db::factory('PDO_MYSQL', $options);
  275. $table = new Bugs(array('db' => $db));
  276. ]]></programlisting>
  277. </example>
  278. </sect3>
  279. <sect3 id="zend.db.table.constructing.default-adapter">
  280. <title>Setting a Default Database Adapter</title>
  281. <para>
  282. The second way to provide a database adapter to a Table class is by declaring an
  283. object of type <classname>Zend_Db_Adapter_Abstract</classname> to be a default
  284. database adapter for all subsequent instances of Tables in your application. You can
  285. do this with the static method
  286. <methodname>Zend_Db_Table_Abstract::setDefaultAdapter()</methodname>. The argument
  287. is an object of type <classname>Zend_Db_Adapter_Abstract</classname>.
  288. </para>
  289. <example id="zend.db.table.constructing.default-adapter.example">
  290. <title>Example of constructing a Table using a the Default Adapter</title>
  291. <programlisting language="php"><![CDATA[
  292. $db = Zend_Db::factory('PDO_MYSQL', $options);
  293. Zend_Db_Table_Abstract::setDefaultAdapter($db);
  294. // Later...
  295. $table = new Bugs();
  296. ]]></programlisting>
  297. </example>
  298. <para>
  299. It can be convenient to create the database adapter object in a central place of
  300. your application, such as the bootstrap, and then store it as the default adapter.
  301. This gives you a means to ensure that the adapter instance is the same throughout
  302. your application. However, setting a default adapter is limited to a single adapter
  303. instance.
  304. </para>
  305. </sect3>
  306. <sect3 id="zend.db.table.constructing.registry">
  307. <title>Storing a Database Adapter in the Registry</title>
  308. <para>
  309. The third way to provide a database adapter to a Table class is by passing a string
  310. in the options array, also identified by the '<property>db</property>' key. The
  311. string is used as a key to the static <classname>Zend_Registry</classname> instance,
  312. where the entry at that key is an object of type
  313. <classname>Zend_Db_Adapter_Abstract</classname>.
  314. </para>
  315. <example id="zend.db.table.constructing.registry.example">
  316. <title>Example of constructing a Table using a Registry key</title>
  317. <programlisting language="php"><![CDATA[
  318. $db = Zend_Db::factory('PDO_MYSQL', $options);
  319. Zend_Registry::set('my_db', $db);
  320. // Later...
  321. $table = new Bugs(array('db' => 'my_db'));
  322. ]]></programlisting>
  323. </example>
  324. <para>
  325. Like setting the default adapter, this gives you the means to ensure that the same
  326. adapter instance is used throughout your application. Using the registry is more
  327. flexible, because you can store more than one adapter instance. A given adapter
  328. instance is specific to a certain <acronym>RDBMS</acronym> brand and database
  329. instance. If your application needs access to multiple databases or even multiple
  330. database brands, then you need to use multiple adapters.
  331. </para>
  332. </sect3>
  333. </sect2>
  334. <sect2 id="zend.db.table.insert">
  335. <title>Inserting Rows to a Table</title>
  336. <para>
  337. You can use the Table object to insert rows into the database table on which the Table
  338. object is based. Use the <methodname>insert()</methodname> method of your Table object.
  339. The argument is an associative array, mapping column names to values.
  340. </para>
  341. <example id="zend.db.table.insert.example">
  342. <title>Example of inserting to a Table</title>
  343. <programlisting language="php"><![CDATA[
  344. $table = new Bugs();
  345. $data = array(
  346. 'created_on' => '2007-03-22',
  347. 'bug_description' => 'Something wrong',
  348. 'bug_status' => 'NEW'
  349. );
  350. $table->insert($data);
  351. ]]></programlisting>
  352. </example>
  353. <para>
  354. By default, the values in your data array are inserted as literal values, using
  355. parameters. If you need them to be treated as <acronym>SQL</acronym> expressions, you
  356. must make sure they are distinct from plain strings. Use an object of type
  357. <classname>Zend_Db_Expr</classname> to do this.
  358. </para>
  359. <example id="zend.db.table.insert.example-expr">
  360. <title>Example of inserting expressions to a Table</title>
  361. <programlisting language="php"><![CDATA[
  362. $table = new Bugs();
  363. $data = array(
  364. 'created_on' => new Zend_Db_Expr('CURDATE()'),
  365. 'bug_description' => 'Something wrong',
  366. 'bug_status' => 'NEW'
  367. );
  368. ]]></programlisting>
  369. </example>
  370. <para>
  371. In the examples of inserting rows above, it is assumed that the table has an
  372. auto-incrementing primary key. This is the default behavior of
  373. <classname>Zend_Db_Table_Abstract</classname>, but there are other types of primary keys
  374. as well. The following sections describe how to support different types of primary keys.
  375. </para>
  376. <sect3 id="zend.db.table.insert.key-auto">
  377. <title>Using a Table with an Auto-incrementing Key</title>
  378. <para>
  379. An auto-incrementing primary key generates a unique integer value for you if you
  380. omit the primary key column from your <acronym>SQL</acronym>
  381. <constant>INSERT</constant> statement.
  382. </para>
  383. <para>
  384. In <classname>Zend_Db_Table_Abstract</classname>, if you define the protected
  385. variable <varname>$_sequence</varname> to be the Boolean value
  386. <constant>TRUE</constant>, then the class assumes that the table has an
  387. auto-incrementing primary key.
  388. </para>
  389. <example id="zend.db.table.insert.key-auto.example">
  390. <title>Example of declaring a Table with auto-incrementing primary key</title>
  391. <programlisting language="php"><![CDATA[
  392. class Bugs extends Zend_Db_Table_Abstract
  393. {
  394. protected $_name = 'bugs';
  395. // This is the default in the Zend_Db_Table_Abstract class;
  396. // you do not need to define this.
  397. protected $_sequence = true;
  398. }
  399. ]]></programlisting>
  400. </example>
  401. <para>
  402. MySQL, Microsoft <acronym>SQL</acronym> Server, and SQLite are examples of
  403. <acronym>RDBMS</acronym> brands that support auto-incrementing primary keys.
  404. </para>
  405. <para>
  406. PostgreSQL has a <constant>SERIAL</constant> notation that implicitly defines a
  407. sequence based on the table and column name, and uses the sequence to generate key
  408. values for new rows. <acronym>IBM</acronym> <acronym>DB2</acronym> has an
  409. <constant>IDENTITY</constant> notation that works similarly. If you use either of
  410. these notations, treat your <classname>Zend_Db_Table</classname> class as having an
  411. auto-incrementing column with respect to declaring the <varname>$_sequence</varname>
  412. member as <constant>TRUE</constant>.
  413. </para>
  414. </sect3>
  415. <sect3 id="zend.db.table.insert.key-sequence">
  416. <title>Using a Table with a Sequence</title>
  417. <para>
  418. A sequence is a database object that generates a unique value, which can be used
  419. as a primary key value in one or more tables of the database.
  420. </para>
  421. <para>
  422. If you define <varname>$_sequence</varname> to be a string, then
  423. <classname>Zend_Db_Table_Abstract</classname> assumes the string to name a sequence
  424. object in the database. The sequence is invoked to generate a new value, and this
  425. value is used in the <constant>INSERT</constant> operation.
  426. </para>
  427. <example id="zend.db.table.insert.key-sequence.example">
  428. <title>Example of declaring a Table with a sequence</title>
  429. <programlisting language="php"><![CDATA[
  430. class Bugs extends Zend_Db_Table_Abstract
  431. {
  432. protected $_name = 'bugs';
  433. protected $_sequence = 'bug_sequence';
  434. }
  435. ]]></programlisting>
  436. </example>
  437. <para>
  438. Oracle, PostgreSQL, and <acronym>IBM</acronym> <acronym>DB2</acronym> are examples
  439. of <acronym>RDBMS</acronym> brands that support sequence objects in the database.
  440. </para>
  441. <para>
  442. PostgreSQL and <acronym>IBM</acronym> <acronym>DB2</acronym> also have syntax that
  443. defines sequences implicitly and associated with columns. If you use this notation,
  444. treat the table as having an auto-incrementing key column. Define the sequence name
  445. as a string only in cases where you would invoke the sequence explicitly to get the
  446. next key value.
  447. </para>
  448. </sect3>
  449. <sect3 id="zend.db.table.insert.key-natural">
  450. <title>Using a Table with a Natural Key</title>
  451. <para>
  452. Some tables have a natural key. This means that the key is not automatically
  453. generated by the table or by a sequence. You must specify the value for the primary
  454. key in this case.
  455. </para>
  456. <para>
  457. If you define the <varname>$_sequence</varname> to be the Boolean value
  458. <constant>FALSE</constant>, then <classname>Zend_Db_Table_Abstract</classname>
  459. assumes that the table has a natural primary key. You must provide values for the
  460. primary key columns in the array of data to the <methodname>insert()</methodname>
  461. method, or else this method throws a <classname>Zend_Db_Table_Exception</classname>.
  462. </para>
  463. <example id="zend.db.table.insert.key-natural.example">
  464. <title>Example of declaring a Table with a natural key</title>
  465. <programlisting language="php"><![CDATA[
  466. class BugStatus extends Zend_Db_Table_Abstract
  467. {
  468. protected $_name = 'bug_status';
  469. protected $_sequence = false;
  470. }
  471. ]]></programlisting>
  472. </example>
  473. <note>
  474. <para>
  475. All <acronym>RDBMS</acronym> brands support tables with natural keys. Examples
  476. of tables that are often declared as having natural keys are lookup tables,
  477. intersection tables in many-to-many relationships, or most tables with compound
  478. primary keys.
  479. </para>
  480. </note>
  481. </sect3>
  482. </sect2>
  483. <sect2 id="zend.db.table.update">
  484. <title>Updating Rows in a Table</title>
  485. <para>
  486. You can update rows in a database table using the <methodname>update()</methodname>
  487. method of a Table class. This method takes two arguments: an associative array of
  488. columns to change and new values to assign to these columns; and an
  489. <acronym>SQL</acronym> expression that is used in a <constant>WHERE</constant> clause,
  490. as criteria for the rows to change in the <constant>UPDATE</constant> operation.
  491. </para>
  492. <example id="zend.db.table.update.example">
  493. <title>Example of updating rows in a Table</title>
  494. <programlisting language="php"><![CDATA[
  495. $table = new Bugs();
  496. $data = array(
  497. 'updated_on' => '2007-03-23',
  498. 'bug_status' => 'FIXED'
  499. );
  500. $where = $table->getAdapter()->quoteInto('bug_id = ?', 1234);
  501. $table->update($data, $where);
  502. ]]></programlisting>
  503. </example>
  504. <para>
  505. Since the table <methodname>update()</methodname> method proxies to the database adapter
  506. <link linkend="zend.db.adapter.write.update"><methodname>update()</methodname></link>
  507. method, the second argument can be an array of <acronym>SQL</acronym> expressions. The
  508. expressions are combined as Boolean terms using an <constant>AND</constant> operator.
  509. </para>
  510. <note>
  511. <para>
  512. The values and identifiers in the <acronym>SQL</acronym> expression are not quoted
  513. for you. If you have values or identifiers that require quoting, you are responsible
  514. for doing this. Use the <methodname>quote()</methodname>,
  515. <methodname>quoteInto()</methodname>, and <methodname>quoteIdentifier()</methodname>
  516. methods of the database adapter.
  517. </para>
  518. </note>
  519. </sect2>
  520. <sect2 id="zend.db.table.delete">
  521. <title>Deleting Rows from a Table</title>
  522. <para>
  523. You can delete rows from a database table using the <methodname>delete()</methodname>
  524. method. This method takes one argument, which is an <acronym>SQL</acronym> expression
  525. that is used in a <constant>WHERE</constant> clause, as criteria for the rows to delete.
  526. </para>
  527. <example id="zend.db.table.delete.example">
  528. <title>Example of deleting rows from a Table</title>
  529. <programlisting language="php"><![CDATA[
  530. $table = new Bugs();
  531. $where = $table->getAdapter()->quoteInto('bug_id = ?', 1235);
  532. $table->delete($where);
  533. ]]></programlisting>
  534. </example>
  535. <para>
  536. Since the table <methodname>delete()</methodname> method proxies to the database adapter
  537. <link linkend="zend.db.adapter.write.delete"><methodname>delete()</methodname></link>
  538. method, the argument can also be an array of <acronym>SQL</acronym> expressions. The
  539. expressions are combined as Boolean terms using an <constant>AND</constant> operator.
  540. </para>
  541. <note>
  542. <para>
  543. The values and identifiers in the <acronym>SQL</acronym> expression are not quoted
  544. for you. If you have values or identifiers that require quoting, you are responsible
  545. for doing this. Use the <methodname>quote()</methodname>,
  546. <methodname>quoteInto()</methodname>, and <methodname>quoteIdentifier()</methodname>
  547. methods of the database adapter.
  548. </para>
  549. </note>
  550. </sect2>
  551. <sect2 id="zend.db.table.find">
  552. <title>Finding Rows by Primary Key</title>
  553. <para>
  554. You can query the database table for rows matching specific values in the primary key,
  555. using the <methodname>find()</methodname> method. The first argument of this method is
  556. either a single value or an array of values to match against the primary key of the
  557. table.
  558. </para>
  559. <example id="zend.db.table.find.example">
  560. <title>Example of finding rows by primary key values</title>
  561. <programlisting language="php"><![CDATA[
  562. $table = new Bugs();
  563. // Find a single row
  564. // Returns a Rowset
  565. $rows = $table->find(1234);
  566. // Find multiple rows
  567. // Also returns a Rowset
  568. $rows = $table->find(array(1234, 5678));
  569. ]]></programlisting>
  570. </example>
  571. <para>
  572. If you specify a single value, the method returns at most one row, because a primary
  573. key cannot have duplicate values and there is at most one row in the database table
  574. matching the value you specify. If you specify multiple values in an array, the method
  575. returns at most as many rows as the number of distinct values you specify.
  576. </para>
  577. <para>
  578. The <methodname>find()</methodname> method might return fewer rows than the number of
  579. values you specify for the primary key, if some of the values don't match any rows in
  580. the database table. The method even may return zero rows. Because the number of rows
  581. returned is variable, the <methodname>find()</methodname> method returns an object of
  582. type <classname>Zend_Db_Table_Rowset_Abstract</classname>.
  583. </para>
  584. <para>
  585. If the primary key is a compound key, that is, it consists of multiple columns, you can
  586. specify the additional columns as additional arguments to the
  587. <methodname>find()</methodname> method. You must provide as many arguments as the number
  588. of columns in the table's primary key.
  589. </para>
  590. <para>
  591. To find multiple rows from a table with a compound primary key, provide an array for
  592. each of the arguments. All of these arrays must have the same number of elements. The
  593. values in each array are formed into tuples in order; for example, the first element
  594. in all the array arguments define the first compound primary key value, then the second
  595. elements of all the arrays define the second compound primary key value, and so on.
  596. </para>
  597. <example id="zend.db.table.find.example-compound">
  598. <title>Example of finding rows by compound primary key values</title>
  599. <para>
  600. The call to <methodname>find()</methodname> below to match multiple rows can match
  601. two rows in the database. The first row must have primary key value (1234, 'ABC'),
  602. and the second row must have primary key value (5678, 'DEF').
  603. </para>
  604. <programlisting language="php"><![CDATA[
  605. class BugsProducts extends Zend_Db_Table_Abstract
  606. {
  607. protected $_name = 'bugs_products';
  608. protected $_primary = array('bug_id', 'product_id');
  609. }
  610. $table = new BugsProducts();
  611. // Find a single row with a compound primary key
  612. // Returns a Rowset
  613. $rows = $table->find(1234, 'ABC');
  614. // Find multiple rows with compound primary keys
  615. // Also returns a Rowset
  616. $rows = $table->find(array(1234, 5678), array('ABC', 'DEF'));
  617. ]]></programlisting>
  618. </example>
  619. </sect2>
  620. <sect2 id="zend.db.table.fetch-all">
  621. <title>Querying for a Set of Rows</title>
  622. <sect3 id="zend.db.table.fetch-all.select">
  623. <title>Select API</title>
  624. <warning>
  625. <para>
  626. The <acronym>API</acronym> for fetch operations has been superseded to allow
  627. a <classname>Zend_Db_Table_Select</classname> object to modify the query.
  628. However, the deprecated usage of the <methodname>fetchRow()</methodname> and
  629. <methodname>fetchAll()</methodname> methods will continue to work without
  630. modification.
  631. </para>
  632. <para>
  633. The following statements are all legal and functionally identical, however
  634. it is recommended to update your code to take advantage of the new usage
  635. where possible.
  636. </para>
  637. <programlisting language="php"><![CDATA[
  638. /**
  639. * Fetching a rowset
  640. */
  641. $rows = $table->fetchAll(
  642. 'bug_status = "NEW"',
  643. 'bug_id ASC',
  644. 10,
  645. 0
  646. );
  647. $rows = $table->fetchAll(
  648. $table->select()
  649. ->where('bug_status = ?', 'NEW')
  650. ->order('bug_id ASC')
  651. ->limit(10, 0)
  652. );
  653. // or with binding
  654. $rows = $table->fetchAll(
  655. $table->select()
  656. ->where('bug_status = :status')
  657. ->bind(array(':status'=>'NEW')
  658. ->order('bug_id ASC')
  659. ->limit(10, 0)
  660. );
  661. /**
  662. * Fetching a single row
  663. */
  664. $row = $table->fetchRow(
  665. 'bug_status = "NEW"',
  666. 'bug_id ASC'
  667. );
  668. $row = $table->fetchRow(
  669. $table->select()
  670. ->where('bug_status = ?', 'NEW')
  671. ->order('bug_id ASC')
  672. );
  673. // or with binding
  674. $row = $table->fetchRow(
  675. $table->select()
  676. ->where('bug_status = :status')
  677. ->bind(array(':status'=>'NEW')
  678. ->order('bug_id ASC')
  679. );
  680. ]]></programlisting>
  681. </warning>
  682. <para>
  683. The <classname>Zend_Db_Table_Select</classname> object is an extension of the
  684. <classname>Zend_Db_Select</classname> object that applies specific restrictions to
  685. a query. The enhancements and restrictions are:
  686. </para>
  687. <itemizedlist>
  688. <listitem>
  689. <para>
  690. You <emphasis>can</emphasis> elect to return a subset of columns within a
  691. fetchRow or fetchAll query. This can provide optimization benefits where
  692. returning a large set of results for all columns is not desirable.
  693. </para>
  694. </listitem>
  695. <listitem>
  696. <para>
  697. You <emphasis>can</emphasis> specify columns that evaluate expressions from
  698. within the selected table. However this will mean that the returned row or
  699. rowset will be <property>readOnly</property> and cannot be used for
  700. <methodname>save()</methodname> operations. A
  701. <classname>Zend_Db_Table_Row</classname> with
  702. <property>readOnly</property> status will throw an exception if a
  703. <methodname>save()</methodname> operation is attempted.
  704. </para>
  705. </listitem>
  706. <listitem>
  707. <para>
  708. You <emphasis>can</emphasis> allow <constant>JOIN</constant> clauses on a
  709. select to allow multi-table lookups.
  710. </para>
  711. </listitem>
  712. <listitem>
  713. <para>
  714. You <emphasis>can not</emphasis> specify columns from a JOINed tabled to be
  715. returned in a row or rowset. Doing so will trigger a <acronym>PHP</acronym>
  716. error. This was done to ensure the integrity of the
  717. <classname>Zend_Db_Table</classname> is retained. i.e. A
  718. <classname>Zend_Db_Table_Row</classname> should only reference columns
  719. derived from its parent table.
  720. </para>
  721. </listitem>
  722. </itemizedlist>
  723. <example id="zend.db.table.qry.rows.set.simple.usage.example">
  724. <title>Simple usage</title>
  725. <programlisting language="php"><![CDATA[
  726. $table = new Bugs();
  727. $select = $table->select();
  728. $select->where('bug_status = ?', 'NEW');
  729. $rows = $table->fetchAll($select);
  730. ]]></programlisting>
  731. </example>
  732. <para>
  733. Fluent interfaces are implemented across the component, so this can be rewritten
  734. this in a more abbreviated form.
  735. </para>
  736. <example id="zend.db.table.qry.rows.set.fluent.interface.example">
  737. <title>Example of fluent interface</title>
  738. <programlisting language="php"><![CDATA[
  739. $table = new Bugs();
  740. $rows =
  741. $table->fetchAll($table->select()->where('bug_status = ?', 'NEW'));
  742. ]]></programlisting>
  743. </example>
  744. </sect3>
  745. <sect3 id="zend.db.table.fetch-all.usage">
  746. <title>Fetching a rowset</title>
  747. <para>
  748. You can query for a set of rows using any criteria other than the primary key
  749. values, using the <methodname>fetchAll()</methodname> method of the Table class.
  750. This method returns an object of type
  751. <classname>Zend_Db_Table_Rowset_Abstract</classname>.
  752. </para>
  753. <example id="zend.db.table.qry.rows.set.finding.row.example">
  754. <title>Example of finding rows by an expression</title>
  755. <programlisting language="php"><![CDATA[
  756. $table = new Bugs();
  757. $select = $table->select()->where('bug_status = ?', 'NEW');
  758. $rows = $table->fetchAll($select);
  759. ]]></programlisting>
  760. </example>
  761. <para>
  762. You may also pass sorting criteria in an <constant>ORDER</constant> BY clause, as
  763. well as count and offset integer values, used to make the query return a specific
  764. subset of rows. These values are used in a <constant>LIMIT</constant> clause, or in
  765. equivalent logic for <acronym>RDBMS</acronym> brands that do not support the
  766. <constant>LIMIT</constant> syntax.
  767. </para>
  768. <example id="zend.db.table.fetch-all.example2">
  769. <title>Example of finding rows by an expression</title>
  770. <programlisting language="php"><![CDATA[
  771. $table = new Bugs();
  772. $order = 'bug_id';
  773. // Return the 21st through 30th rows
  774. $count = 10;
  775. $offset = 20;
  776. $select = $table->select()->where('bug_status = ?', 'NEW')
  777. ->order($order)
  778. ->limit($count, $offset);
  779. $rows = $table->fetchAll($select);
  780. ]]></programlisting>
  781. </example>
  782. <para>
  783. All of the arguments above are optional. If you omit the <constant>ORDER</constant>
  784. clause, the result set includes rows from the table in an unpredictable order. If
  785. no <constant>LIMIT</constant> clause is set, you retrieve every row in the table
  786. that matches the <constant>WHERE</constant> clause.
  787. </para>
  788. </sect3>
  789. <sect3 id="zend.db.table.advanced.usage">
  790. <title>Advanced usage</title>
  791. <para>
  792. For more specific and optimized requests, you may wish to limit the number of
  793. columns returned in a row or rowset. This can be achieved by passing a
  794. <constant>FROM</constant> clause to the select object. The first argument in the
  795. <constant>FROM</constant> clause is identical to that of a
  796. <classname>Zend_Db_Select</classname> object with the addition of being able to pass
  797. an instance of <classname>Zend_Db_Table_Abstract</classname> and have it
  798. automatically determine the table name.
  799. </para>
  800. <example id="zend.db.table.qry.rows.set.retrieving.a.example">
  801. <title>Retrieving specific columns</title>
  802. <programlisting language="php"><![CDATA[
  803. $table = new Bugs();
  804. $select = $table->select();
  805. $select->from($table, array('bug_id', 'bug_description'))
  806. ->where('bug_status = ?', 'NEW');
  807. $rows = $table->fetchAll($select);
  808. ]]></programlisting>
  809. </example>
  810. <important>
  811. <para>
  812. The rowset contains rows that are still 'valid' - they simply contain a
  813. subset of the columns of a table. If a <methodname>save()</methodname>
  814. method is called on a partial row then only the fields available will be
  815. modified.
  816. </para>
  817. </important>
  818. <para>
  819. You can also specify expressions within a <constant>FROM</constant> clause and have
  820. these returned as a readOnly row or rowset. In this example we will return a rows
  821. from the bugs table that show an aggregate of the number of new bugs reported by
  822. individuals. Note the <constant>GROUP</constant> clause. The 'count' column will be
  823. made available to the row for evaluation and can be accessed as if it were part of
  824. the schema.
  825. </para>
  826. <example id="zend.db.table.qry.rows.set.retrieving.b.example">
  827. <title>Retrieving expressions as columns</title>
  828. <programlisting language="php"><![CDATA[
  829. $table = new Bugs();
  830. $select = $table->select();
  831. $select->from($table,
  832. array('COUNT(reported_by) as `count`', 'reported_by'))
  833. ->where('bug_status = ?', 'NEW')
  834. ->group('reported_by');
  835. $rows = $table->fetchAll($select);
  836. ]]></programlisting>
  837. </example>
  838. <para>
  839. You can also use a lookup as part of your query to further refine your fetch
  840. operations. In this example the accounts table is queried as part of a search for
  841. all new bugs reported by 'Bob'.
  842. </para>
  843. <example id="zend.db.table.qry.rows.set.refine.example">
  844. <title>Using a lookup table to refine the results of fetchAll()</title>
  845. <programlisting language="php"><![CDATA[
  846. $table = new Bugs();
  847. // retrieve with from part set, important when joining
  848. $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
  849. $select->setIntegrityCheck(false)
  850. ->where('bug_status = ?', 'NEW')
  851. ->join('accounts', 'accounts.account_name = bugs.reported_by')
  852. ->where('accounts.account_name = ?', 'Bob');
  853. $rows = $table->fetchAll($select);
  854. ]]></programlisting>
  855. </example>
  856. <para>
  857. The <classname>Zend_Db_Table_Select</classname> is primarily used to constrain and
  858. validate so that it may enforce the criteria for a legal <constant>SELECT</constant>
  859. query. However there may be certain cases where you require the flexibility of the
  860. <classname>Zend_Db_Table_Row</classname> component and do not require a writable or
  861. deletable row. for this specific user case, it is possible to retrieve a row or
  862. rowset by passing a <constant>FALSE</constant> value to
  863. <methodname>setIntegrityCheck()</methodname>. The resulting row or rowset will be
  864. returned as a 'locked' row (meaning the <methodname>save()</methodname>,
  865. <methodname>delete()</methodname> and any field-setting methods will throw an
  866. exception).
  867. </para>
  868. <example id="zend.db.table.qry.rows.set.integrity.example">
  869. <title>
  870. Removing the integrity check on Zend_Db_Table_Select to allow JOINed rows
  871. </title>
  872. <programlisting language="php"><![CDATA[
  873. $table = new Bugs();
  874. $select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
  875. ->setIntegrityCheck(false);
  876. $select->where('bug_status = ?', 'NEW')
  877. ->join('accounts',
  878. 'accounts.account_name = bugs.reported_by',
  879. 'account_name')
  880. ->where('accounts.account_name = ?', 'Bob');
  881. $rows = $table->fetchAll($select);
  882. ]]></programlisting>
  883. </example>
  884. </sect3>
  885. </sect2>
  886. <sect2 id="zend.db.table.fetch-row">
  887. <title>Querying for a Single Row</title>
  888. <para>
  889. You can query for a single row using criteria similar to that of the
  890. <methodname>fetchAll()</methodname> method.
  891. </para>
  892. <example id="zend.db.table.fetch-row.example1">
  893. <title>Example of finding a single row by an expression</title>
  894. <programlisting language="php"><![CDATA[
  895. $table = new Bugs();
  896. $select = $table->select()->where('bug_status = ?', 'NEW')
  897. ->order('bug_id');
  898. $row = $table->fetchRow($select);
  899. ]]></programlisting>
  900. </example>
  901. <para>
  902. This method returns an object of type <classname>Zend_Db_Table_Row_Abstract</classname>.
  903. If the search criteria you specified match no rows in the database table, then
  904. <methodname>fetchRow()</methodname> returns <acronym>PHP</acronym>'s
  905. <constant>NULL</constant> value.
  906. </para>
  907. </sect2>
  908. <sect2 id="zend.db.table.info">
  909. <title>Retrieving Table Metadata Information</title>
  910. <para>
  911. The <classname>Zend_Db_Table_Abstract</classname> class provides some information about
  912. its metadata. The <methodname>info()</methodname> method returns an array structure with
  913. information about the table, its columns and primary key, and other metadata.
  914. </para>
  915. <example id="zend.db.table.info.example">
  916. <title>Example of getting the table name</title>
  917. <programlisting language="php"><![CDATA[
  918. $table = new Bugs();
  919. $info = $table->info();
  920. echo "The table name is " . $info['name'] . "\n";
  921. ]]></programlisting>
  922. </example>
  923. <para>
  924. The keys of the array returned by the <methodname>info()</methodname> method are
  925. described below:
  926. </para>
  927. <itemizedlist>
  928. <listitem>
  929. <para>
  930. <emphasis>name</emphasis> => the name of the table.
  931. </para>
  932. </listitem>
  933. <listitem>
  934. <para>
  935. <emphasis>cols</emphasis> => an array, naming the columns of
  936. the table.
  937. </para>
  938. </listitem>
  939. <listitem>
  940. <para>
  941. <emphasis>primary</emphasis> => an array, naming the columns in
  942. the primary key.
  943. </para>
  944. </listitem>
  945. <listitem>
  946. <para>
  947. <emphasis>metadata</emphasis> => an associative array, mapping
  948. column names to information about the columns. This is the information returned
  949. by the <methodname>describeTable()</methodname> method.
  950. </para>
  951. </listitem>
  952. <listitem>
  953. <para>
  954. <emphasis>rowClass</emphasis> => the name of the concrete class
  955. used for Row objects returned by methods of this table instance. This defaults
  956. to <classname>Zend_Db_Table_Row</classname>.
  957. </para>
  958. </listitem>
  959. <listitem>
  960. <para>
  961. <emphasis>rowsetClass</emphasis> => the name of the concrete
  962. class used for Rowset objects returned by methods of this table instance. This
  963. defaults to <classname>Zend_Db_Table_Rowset</classname>.
  964. </para>
  965. </listitem>
  966. <listitem>
  967. <para>
  968. <emphasis>referenceMap</emphasis> => an associative array, with
  969. information about references from this table to any parent tables. See
  970. <link linkend="zend.db.table.relationships.defining">this chapter</link>.
  971. </para>
  972. </listitem>
  973. <listitem>
  974. <para>
  975. <emphasis>dependentTables</emphasis> => an array of class names
  976. of tables that reference this table. See
  977. <link linkend="zend.db.table.relationships.defining">this chapter</link>.
  978. </para>
  979. </listitem>
  980. <listitem>
  981. <para>
  982. <emphasis>schema</emphasis> => the name of the schema (or
  983. database or tablespace) for this table.
  984. </para>
  985. </listitem>
  986. </itemizedlist>
  987. </sect2>
  988. <sect2 id="zend.db.table.metadata.caching">
  989. <title>Caching Table Metadata</title>
  990. <para>
  991. By default, <classname>Zend_Db_Table_Abstract</classname> queries the
  992. underlying database for <link linkend="zend.db.table.info">table
  993. metadata</link> whenever that data is needed to perform table
  994. operations. The table object fetches the table metadata from the
  995. database using the adapter's <methodname>describeTable()</methodname> method.
  996. Operations requiring this introspection include:
  997. </para>
  998. <itemizedlist>
  999. <listitem><para><methodname>insert()</methodname></para></listitem>
  1000. <listitem><para><methodname>find()</methodname></para></listitem>
  1001. <listitem><para><methodname>info()</methodname></para></listitem>
  1002. </itemizedlist>
  1003. <para>
  1004. In some circumstances, particularly when many table objects are instantiated against
  1005. the same database table, querying the database for the table metadata for each instance
  1006. may be undesirable from a performance standpoint. In such cases, users may benefit by
  1007. caching the table metadata retrieved from the database.
  1008. </para>
  1009. <para>
  1010. There are two primary ways in which a user may take advantage of table metadata
  1011. caching:
  1012. </para>
  1013. <itemizedlist>
  1014. <listitem>
  1015. <para>
  1016. <emphasis>Call
  1017. <methodname>Zend_Db_Table_Abstract::setDefaultMetadataCache()</methodname></emphasis>
  1018. - This allows a developer to once set the default cache object to be used
  1019. for all table classes.
  1020. </para>
  1021. </listitem>
  1022. <listitem>
  1023. <para>
  1024. <emphasis>Configure
  1025. <methodname>Zend_Db_Table_Abstract::__construct()</methodname></emphasis> -
  1026. This allows a developer to set the cache object to be used for a particular
  1027. table class instance.
  1028. </para>
  1029. </listitem>
  1030. </itemizedlist>
  1031. <para>
  1032. In both cases, the cache specification must be either <constant>NULL</constant> (i.e.,
  1033. no cache used) or an instance of
  1034. <link linkend="zend.cache.frontends.core"><classname>Zend_Cache_Core</classname></link>.
  1035. The methods may be used in conjunction when it is desirable to have both a default
  1036. metadata cache and the ability to change the cache for individual table objects.
  1037. </para>
  1038. <example id="zend.db.table.metadata.caching-default">
  1039. <title>Using a Default Metadata Cache for all Table Objects</title>
  1040. <para>
  1041. The following code demonstrates how to set a default metadata cache to be used for
  1042. all table objects:
  1043. </para>
  1044. <programlisting language="php"><![CDATA[
  1045. // First, set up the Cache
  1046. $frontendOptions = array(
  1047. 'automatic_serialization' => true
  1048. );
  1049. $backendOptions = array(
  1050. 'cache_dir' => 'cacheDir'
  1051. );
  1052. $cache = Zend_Cache::factory('Core',
  1053. 'File',
  1054. $frontendOptions,
  1055. $backendOptions);
  1056. // Next, set the cache to be used with all table objects
  1057. Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
  1058. // A table class is also needed
  1059. class Bugs extends Zend_Db_Table_Abstract
  1060. {
  1061. // ...
  1062. }
  1063. // Each instance of Bugs now uses the default metadata cache
  1064. $bugs = new Bugs();
  1065. ]]></programlisting>
  1066. </example>
  1067. <example id="zend.db.table.metadata.caching-instance">
  1068. <title>Using a Metadata Cache for a Specific Table Object</title>
  1069. <para>
  1070. The following code demonstrates how to set a metadata cache for a specific table
  1071. object instance:
  1072. </para>
  1073. <programlisting language="php"><![CDATA[
  1074. // First, set up the Cache
  1075. $frontendOptions = array(
  1076. 'automatic_serialization' => true
  1077. );
  1078. $backendOptions = array(
  1079. 'cache_dir' => 'cacheDir'
  1080. );
  1081. $cache = Zend_Cache::factory('Core',
  1082. 'File',
  1083. $frontendOptions,
  1084. $backendOptions);
  1085. // A table class is also needed
  1086. class Bugs extends Zend_Db_Table_Abstract
  1087. {
  1088. // ...
  1089. }
  1090. // Configure an instance upon instantiation
  1091. $bugs = new Bugs(array('metadataCache' => $cache));
  1092. ]]></programlisting>
  1093. </example>
  1094. <note>
  1095. <title>Automatic Serialization with the Cache Frontend</title>
  1096. <para>
  1097. Since the information returned from the adapter's
  1098. <methodname>describeTable()</methodname> method is an array, ensure that the
  1099. <property>automatic_serialization</property> option is set to
  1100. <constant>TRUE</constant> for the <classname>Zend_Cache_Core</classname> frontend.
  1101. </para>
  1102. </note>
  1103. <para>
  1104. Though the above examples use <classname>Zend_Cache_Backend_File</classname>, developers
  1105. may use whatever cache backend is appropriate for the situation. Please see
  1106. <link linkend="zend.cache">Zend_Cache</link> for more information.
  1107. </para>
  1108. <sect3 id="zend.db.table.metadata.caching.hardcoding">
  1109. <title>Hardcoding Table Metadata</title>
  1110. <para>
  1111. To take metadata caching a step further, you can also choose to
  1112. hardcode metadata. In this particular case, however, any changes
  1113. to the table schema will require a change in your code. As such,
  1114. it is only recommended for those who are optimizing for
  1115. production usage.
  1116. </para>
  1117. <para>
  1118. The metadata structure is as follows:
  1119. </para>
  1120. <programlisting language="php"><![CDATA[
  1121. protected $_metadata = array(
  1122. '<column_name>' => array(
  1123. 'SCHEMA_NAME' => <string>,
  1124. 'TABLE_NAME' => <string>,
  1125. 'COLUMN_NAME' => <string>,
  1126. 'COLUMN_POSITION' => <int>,
  1127. 'DATA_TYPE' => <string>,
  1128. 'DEFAULT' => NULL|<value>,
  1129. 'NULLABLE' => <bool>,
  1130. 'LENGTH' => <string - length>,
  1131. 'SCALE' => NULL|<value>,
  1132. 'PRECISION' => NULL|<value>,
  1133. 'UNSIGNED' => NULL|<bool>,
  1134. 'PRIMARY' => <bool>,
  1135. 'PRIMARY_POSITION' => <int>,
  1136. 'IDENTITY' => <bool>,
  1137. ),
  1138. // additional columns...
  1139. );
  1140. ]]></programlisting>
  1141. <para>
  1142. An easy way to get the appropriate values is to use the metadata
  1143. cache, and then to deserialize values stored in the cache.
  1144. </para>
  1145. <para>
  1146. You can disable this optimization by turning of the
  1147. <property>metadataCacheInClass</property> flag:
  1148. </para>
  1149. <programlisting language="php"><![CDATA[
  1150. // At instantiation:
  1151. $bugs = new Bugs(array('metadataCacheInClass' => false));
  1152. // Or later:
  1153. $bugs->setMetadataCacheInClass(false);
  1154. ]]></programlisting>
  1155. <para>
  1156. The flag is enabled by default, which ensures that the
  1157. <varname>$_metadata</varname> array is only populated once per
  1158. instance.
  1159. </para>
  1160. </sect3>
  1161. </sect2>
  1162. <sect2 id="zend.db.table.extending">
  1163. <title>Customizing and Extending a Table Class</title>
  1164. <sect3 id="zend.db.table.extending.row-rowset">
  1165. <title>Using Custom Row or Rowset Classes</title>
  1166. <para>
  1167. By default, methods of the Table class return a Rowset in instances of the concrete
  1168. class <classname>Zend_Db_Table_Rowset</classname>, and Rowsets contain a collection
  1169. of instances of the concrete class <classname>Zend_Db_Table_Row</classname> You can
  1170. specify an alternative class to use for either of these, but they must be classes
  1171. that extend <classname>Zend_Db_Table_Rowset_Abstract</classname> and
  1172. <classname>Zend_Db_Table_Row_Abstract</classname>, respectively.
  1173. </para>
  1174. <para>
  1175. You can specify Row and Rowset classes using the Table constructor's options array,
  1176. in keys '<property>rowClass</property>' and '<property>rowsetClass</property>'
  1177. respectively. Specify the names of the classes using strings.
  1178. </para>
  1179. <example id="zend.db.table.extending.row-rowset.example">
  1180. <title>Example of specifying the Row and Rowset classes</title>
  1181. <programlisting language="php"><![CDATA[
  1182. class My_Row extends Zend_Db_Table_Row_Abstract
  1183. {
  1184. ...
  1185. }
  1186. class My_Rowset extends Zend_Db_Table_Rowset_Abstract
  1187. {
  1188. ...
  1189. }
  1190. $table = new Bugs(
  1191. array(
  1192. 'rowClass' => 'My_Row',
  1193. 'rowsetClass' => 'My_Rowset'
  1194. )
  1195. );
  1196. $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
  1197. // Returns an object of type My_Rowset,
  1198. // containing an array of objects of type My_Row.
  1199. $rows = $table->fetchAll($where);
  1200. ]]></programlisting>
  1201. </example>
  1202. <para>
  1203. You can change the classes by specifying them with the
  1204. <methodname>setRowClass()</methodname> and <methodname>setRowsetClass()</methodname>
  1205. methods. This applies to rows and rowsets created subsequently; it does not change
  1206. the class of any row or rowset objects you have created previously.
  1207. </para>
  1208. <example id="zend.db.table.extending.row-rowset.example2">
  1209. <title>Example of changing the Row and Rowset classes</title>
  1210. <programlisting language="php"><![CDATA[
  1211. $table = new Bugs();
  1212. $where = $table->getAdapter()->quoteInto('bug_status = ?', 'NEW')
  1213. // Returns an object of type Zend_Db_Table_Rowset
  1214. // containing an array of objects of type Zend_Db_Table_Row.
  1215. $rowsStandard = $table->fetchAll($where);
  1216. $table->setRowClass('My_Row');
  1217. $table->setRowsetClass('My_Rowset');
  1218. // Returns an object of type My_Rowset,
  1219. // containing an array of objects of type My_Row.
  1220. $rowsCustom = $table->fetchAll($where);
  1221. // The $rowsStandard object still exists, and it is unchanged.
  1222. ]]></programlisting>
  1223. </example>
  1224. <para>
  1225. For more information on the Row and Rowset classes, see
  1226. <link linkend="zend.db.table.row">this chapter</link> and <link
  1227. linkend="zend.db.table.rowset">this one</link>.
  1228. </para>
  1229. </sect3>
  1230. <sect3 id="zend.db.table.extending.insert-update">
  1231. <title>Defining Custom Logic for Insert, Update, and Delete</title>
  1232. <para>
  1233. You can override the <methodname>insert()</methodname> and
  1234. <methodname>update()</methodname> methods in your Table class. This gives you the
  1235. opportunity to implement custom code that is executed before performing the database
  1236. operation. Be sure to call the parent class method when you are done.
  1237. </para>
  1238. <example id="zend.db.table.extending.insert-update.example">
  1239. <title>Custom logic to manage timestamps</title>
  1240. <programlisting language="php"><![CDATA[
  1241. class Bugs extends Zend_Db_Table_Abstract
  1242. {
  1243. protected $_name = 'bugs';
  1244. public function insert(array $data)
  1245. {
  1246. // add a timestamp
  1247. if (empty($data['created_on'])) {
  1248. $data['created_on'] = time();
  1249. }
  1250. return parent::insert($data);
  1251. }
  1252. public function update(array $data, $where)
  1253. {
  1254. // add a timestamp
  1255. if (empty($data['updated_on'])) {
  1256. $data['updated_on'] = time();
  1257. }
  1258. return parent::update($data, $where);
  1259. }
  1260. }
  1261. ]]></programlisting>
  1262. </example>
  1263. <para>
  1264. You can also override the <methodname>delete()</methodname> method.
  1265. </para>
  1266. </sect3>
  1267. <sect3 id="zend.db.table.extending.finders">
  1268. <title>Define Custom Search Methods in Zend_Db_Table</title>
  1269. <para>
  1270. You can implement custom query methods in your Table class, if you have frequent
  1271. need to do queries against this table with specific criteria. Most queries can be
  1272. written using <methodname>fetchAll()</methodname>, but this requires that you
  1273. duplicate code to form the query conditions if you need to run the query in several
  1274. places in your application. Therefore it can be convenient to implement a method in
  1275. the Table class to perform frequently-used queries against this table.
  1276. </para>
  1277. <example id="zend.db.table.extending.finders.example">
  1278. <title>Custom method to find bugs by status</title>
  1279. <programlisting language="php"><![CDATA[
  1280. class Bugs extends Zend_Db_Table_Abstract
  1281. {
  1282. protected $_name = 'bugs';
  1283. public function findByStatus($status)
  1284. {
  1285. $where = $this->getAdapter()->quoteInto('bug_status = ?', $status);
  1286. return $this->fetchAll($where, 'bug_id');
  1287. }
  1288. }
  1289. ]]></programlisting>
  1290. </example>
  1291. </sect3>
  1292. <sect3 id="zend.db.table.extending.inflection">
  1293. <title>Define Inflection in Zend_Db_Table</title>
  1294. <para>
  1295. Some people prefer that the table class name match a table name in the
  1296. <acronym>RDBMS</acronym> by using a string transformation called
  1297. <emphasis>inflection</emphasis>.
  1298. </para>
  1299. <para>
  1300. For example, if your table class name is "BugsProducts", it would
  1301. match the physical table in the database called "bugs_products", if
  1302. you omit the explicit declaration of the <varname>$_name</varname> class property.
  1303. In this inflection mapping, the class name spelled in "CamelCase" format would be
  1304. transformed to lower case, and words are separated with an underscore.
  1305. </para>
  1306. <para>
  1307. You can specify the database table name independently from the class name by
  1308. declaring the table name with the <varname>$_name</varname> class property in each
  1309. of your table classes.
  1310. </para>
  1311. <para>
  1312. <classname>Zend_Db_Table_Abstract</classname> performs no inflection to map the
  1313. class name to the table name. If you omit the declaration of
  1314. <varname>$_name</varname> in your table class, the class maps to a database table
  1315. that matches the spelling of the class name exactly.
  1316. </para>
  1317. <para>
  1318. It is inappropriate to transform identifiers from the database, because this can
  1319. lead to ambiguity or make some identifiers inaccessible. Using the
  1320. <acronym>SQL</acronym> identifiers exactly as they appear in the database makes
  1321. <classname>Zend_Db_Table_Abstract</classname> both simpler and more flexible.
  1322. </para>
  1323. <para>
  1324. If you prefer to use inflection, then you must implement the transformation
  1325. yourself, by overriding the <methodname>_setupTableName()</methodname> method in
  1326. your Table classes. One way to do this is to define an abstract class that extends
  1327. <classname>Zend_Db_Table_Abstract</classname>, and then the rest of your tables
  1328. extend your new abstract class.
  1329. </para>
  1330. <example id="zend.db.table.extending.inflection.example">
  1331. <title>Example of an abstract table class that implements inflection</title>
  1332. <programlisting language="php"><![CDATA[
  1333. abstract class MyAbstractTable extends Zend_Db_Table_Abstract
  1334. {
  1335. protected function _setupTableName()
  1336. {
  1337. if (!$this->_name) {
  1338. $this->_name = myCustomInflector(get_class($this));
  1339. }
  1340. parent::_setupTableName();
  1341. }
  1342. }
  1343. class BugsProducts extends MyAbstractTable
  1344. {
  1345. }
  1346. ]]></programlisting>
  1347. </example>
  1348. <para>
  1349. You are responsible for writing the functions to perform inflection transformation.
  1350. Zend Framework does not provide such a function.
  1351. </para>
  1352. </sect3>
  1353. </sect2>
  1354. </sect1>
  1355. <!--
  1356. vim:se ts=4 sw=4 et:
  1357. -->