Zend_Db_Table.xml 63 KB

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