c6820399c43488641d9bb7ca92cc27fd342f59de
[Packages/TYPO3.CMS.git] / typo3 / sysext / adodb / adodb / docs / docs-active-record.htm
1 <html>
2 <style>
3 pre {
4 background-color: #eee;
5 padding: 0.75em 1.5em;
6 font-size: 12px;
7 border: 1px solid #ddd;
8 }
9
10 li,p {
11 font-family: Arial, Helvetica, sans-serif ;
12 }
13 </style>
14 <title>ADOdb Active Record</title>
15 <body>
16 <h1>ADOdb Active Record</h1>
17 <p> (c) 2000-2006 John Lim (jlim#natsoft.com)</p>
18 <p><font size="1">This software is dual licensed using BSD-Style and LGPL. This
19 means you can use it in compiled proprietary and commercial products.</font></p>
20 <p><hr>
21 <ol>
22
23 <h3><li>Introduction</h3>
24 <p>
25 ADOdb_Active_Record is an Object Relation Mapping (ORM) implementation using PHP. In an ORM system, the tables and rows of the database are abstracted into native PHP objects. This allows the programmer to focus more on manipulating the data and less on writing SQL queries.
26 <p>
27 This implementation differs from Zend Framework's implementation in the following ways:
28 <ul>
29 <li>Works with PHP4 and PHP5 and provides equivalent functionality in both versions of PHP.<p>
30 <li>ADOdb_Active_Record works when you are connected to multiple databases. Zend's only works when connected to a default database.<p>
31 <li>Support for $ADODB_ASSOC_CASE. The field names are upper-cased, lower-cased or left in natural case depending on this setting.<p>
32 <li>No field name conversion to camel-caps style, unlike Zend's implementation which will convert field names such as 'first_name' to 'firstName'.<p>
33 <li>New ADOConnection::GetActiveRecords() and ADOConnection::GetActiveRecordsClass() functions in adodb.inc.php.<p>
34 <li>Caching of table metadata so it is only queried once per table, no matter how many Active Records are created.<p>
35 <li>The additional functionality is described <a href=#additional>below</a>.
36 </ul>
37 <P>
38 ADOdb_Active_Record is designed upon the principles of the "ActiveRecord" design pattern, which was first described by Martin Fowler. The ActiveRecord pattern has been implemented in many forms across the spectrum of programming languages. ADOdb_Active_Record attempts to represent the database as closely to native PHP objects as possible.
39 <p>
40 ADOdb_Active_Record maps a database table to a PHP class, and each instance of that class represents a table row. Relations between tables can also be defined, allowing the ADOdb_Active_Record objects to be nested.
41 <p>
42
43 <h3><li>Setting the Database Connection</h3>
44 <p>
45 The first step to using ADOdb_Active_Record is to set the default connection that an ADOdb_Active_Record objects will use to connect to a database.
46
47 <pre>
48 require_once('adodb/adodb-active-record.php');
49
50 $db = new ADOConnection('mysql://root:pwd@localhost/dbname');
51 ADOdb_Active_Record::SetDatabaseAdapter($db);
52 </pre>
53
54 <h3><li>Table Rows as Objects</h3>
55 <p>
56 First, let's create a temporary table in our MySQL database that we can use for demonstrative purposes throughout the rest of this tutorial. We can do this by sending a CREATE query:
57
58 <pre>
59 $db->Execute("CREATE TEMPORARY TABLE `persons` (
60 `id` int(10) unsigned NOT NULL auto_increment,
61 `name_first` varchar(100) NOT NULL default '',
62 `name_last` varchar(100) NOT NULL default '',
63 `favorite_color` varchar(100) NOT NULL default '',
64 PRIMARY KEY (`id`)
65 ) ENGINE=MyISAM;
66 ");
67 </pre>
68 <p>
69 ADOdb_Active_Record's are object representations of table rows. Each table in the database is represented by a class in PHP. To begin working with a table as a ADOdb_Active_Record, a class that extends ADOdb_Active_Records needs to be created for it.
70
71 <pre>
72 class Person extends ADOdb_Active_Record{}
73 $person = new Person();
74 </pre>
75
76 <p>
77 In the above example, a new ADOdb_Active_Record object $person was created to access the "persons" table. Zend_Db_DataObject takes the name of the class, pluralizes it (according to American English rules), and assumes that this is the name of the table in the database.
78 <p>
79 This kind of behavior is typical of ADOdb_Active_Record. It will assume as much as possible by convention rather than explicit configuration. In situations where it isn't possible to use the conventions that ADOdb_Active_Record expects, options can be overridden as we'll see later.
80
81 <h3><li>Table Columns as Object Properties</h3>
82 <p>
83 When the $person object was instantiated, ADOdb_Active_Record read the table metadata from the database itself, and then exposed the table's columns (fields) as object properties.
84 <p>
85 Our "persons" table has three fields: "name_first", "name_last", and "favorite_color". Each of these fields is now a property of the $person object. To see all these properties, use the ADOdb_Active_Record::getAttributeNames() method:
86 <pre>
87 var_dump($person->getAttributeNames());
88
89 /**
90 * Outputs the following:
91 * array(4) {
92 * [0]=>
93 * string(2) "id"
94 * [1]=>
95 * string(9) "name_first"
96 * [2]=>
97 * string(8) "name_last"
98 * [3]=>
99 * string(13) "favorite_color"
100 * }
101 */
102 </pre>
103 <p>
104 One big difference between ADOdb and Zend's implementation is we do not automatically convert to camelCaps style.
105 <p>
106 <h3><li>Inserting and Updating a Record</h3><p>
107
108 An ADOdb_Active_Record object is a representation of a single table row. However, when our $person object is instantiated, it does not reference any particular row. It is a blank record that does not yet exist in the database. An ADOdb_Active_Record object is considered blank when its primary key is NULL. The primary key in our persons table is "id".
109 <p>
110 To insert a new record into the database, change the object's properties and then call the ADOdb_Active_Record::save() method:
111 <pre>
112 $person = new Person();
113 $person->nameFirst = 'Andi';
114 $person->nameLast = 'Gutmans';
115 $person->save();
116 </pre>
117 <p>
118 Oh, no! The above code snippet does not insert a new record into the database. Instead, outputs an error:
119 <pre>
120 1048: Column 'name_first' cannot be null
121 </pre>
122 <p>
123 This error occurred because MySQL rejected the INSERT query that was generated by ADOdb_Active_Record. If exceptions are enabled in ADOdb and you are using PHP5, an error will be thrown. In the definition of our table, we specified all of the fields as NOT NULL; i.e., they must contain a value.
124 <p>
125 ADOdb_Active_Records are bound by the same contraints as the database tables they represent. If the field in the database cannot be NULL, the corresponding property in the ADOdb_Active_Record also cannot be NULL. In the example above, we failed to set the property $person->favoriteColor, which caused the INSERT to be rejected by MySQL.
126 <p>
127 To insert a new ADOdb_Active_Record in the database, populate all of ADOdb_Active_Record's properties so that they satisfy the constraints of the database table, and then call the save() method:
128 <pre>
129 /**
130 * Calling the save() method will successfully INSERT
131 * this $person into the database table.
132 */
133 $person = new Person();
134 $person->name_first = 'Andi';
135 $person->name_last = 'Gutmans';
136 $person->favorite_color = 'blue';
137 $person->save();
138 </pre>
139 <p>
140 Once this $person has been INSERTed into the database by calling save(), the primary key can now be read as a property. Since this is the first row inserted into our temporary table, its "id" will be 1:
141 <pre>
142 var_dump($person->id);
143
144 /**
145 * Outputs the following:
146 * string(1)
147 */
148 </pre>
149 <p>
150 From this point on, updating it is simply a matter of changing the object's properties and calling the save() method again:
151
152 <pre>
153 $person->favorite_color = 'red';
154 $person->save();
155 </pre>
156 <p>
157 The code snippet above will change the favorite color to red, and then UPDATE the record in the database.
158
159 <a name=additional>
160 <h2>ADOdb Specific Functionality</h2>
161 <h3><li>Setting the Table Name</h3>
162 <p>The default behaviour on creating an ADOdb_Active_Record is to "pluralize" the class name and use that as the table name. Often, this is not the case. For example, the Person class could be reading from the "People" table. We provide a constructor parameter to override the default table naming behaviour.
163 <pre>
164 class Person extends ADOdb_Active_Record{}
165 $person = new Person('People');
166 </pre>
167 <h3><li>$ADODB_ASSOC_CASE</h3>
168 <p>This allows you to control the case of field names and properties. For example, all field names in Oracle are upper-case by default. So you
169 can force field names to be lowercase using $ADODB_ASSOC_CASE. Legal values are as follows:
170 <pre>
171 0: lower-case
172 1: upper-case
173 2: native-case
174 </pre>
175 <p>So to force all Oracle field names to lower-case, use
176 <pre>
177 $ADODB_ASSOC_CASE = 0;
178 $person = new Person('People');
179 $person->name = 'Lily';
180 $ADODB_ASSOC_CASE = 2;
181 $person2 = new Person('People');
182 $person2->NAME = 'Lily';
183 </pre>
184
185 <p>Also see <a href=http://phplens.com/adodb/reference.constants.adodb_assoc_case.html>$ADODB_ASSOC_CASE</a>.
186
187 <h3><li>ADOdb_Active_Record::Save</h3>
188 <p>
189 Saves a record by executing an INSERT or UPDATE SQL statement as appropriate.
190 <p>Returns false on unsuccessful INSERT, true if successsful INSERT.
191 <p>Returns 0 on failed UPDATE, and 1 on UPDATE if data has changed, and -1 if no data was changed, so no UPDATE statement was executed.
192
193 <h3><li>ADOdb_Active_Record::Replace</h3>
194 <p>
195 ADOdb supports replace functionality, whereby the record is inserted if it does not exists, or updated otherwise.
196 <pre>
197 $rec = new ADOdb_Active_Record("product");
198 $rec->name = 'John';
199 $rec->tel_no = '34111145';
200 $ok = $rec->replace(); // 0=failure, 1=update, 2=insert
201 </pre>
202
203
204 <h3><li>ADOdb_Active_Record::Load()</h3>
205 <p>Sometimes, we want to load a single record into an Active Record. We can do so using:
206 <pre>
207 $person->load("id=3");
208
209 // or using bind parameters
210
211 $person->load("id=?", array(3));
212 </pre>
213 <p>Returns false if an error occurs.
214
215 <h3><li>Error Handling and Debugging</h3>
216 <p>
217 In PHP5, if adodb-exceptions.inc.php is included, then errors are thrown. Otherwise errors are handled by returning a value. False by default means an error has occurred. You can get the last error message using the ErrorMsg() function.
218 <p>
219 To check for errors in ADOdb_Active_Record, do not poll ErrorMsg() as the last error message will always be returned, even if it occurred several operations ago. Do this instead:
220 <pre>
221 # right!
222 $ok = $rec->Save();
223 if (!$ok) $err = $rec->ErrorMsg();
224
225 # wrong :(
226 $rec->Save();
227 if ($rec->ErrorMsg()) echo "Wrong way to detect error";
228 </pre>
229 <p>The ADOConnection::Debug property is obeyed. So
230 if $db->debug is enabled, then ADOdb_Active_Record errors are also outputted to standard output and written to the browser.
231
232 <h3><li>ADOdb_Active_Record::Set()</h3>
233 <p>You can convert an array to an ADOdb_Active_Record using Set(). The array must be numerically indexed, and have all fields of the table defined in the array. The elements of the array must be in the table's natural order too.
234 <pre>
235 $row = $db->GetRow("select * from tablex where id=$id");
236
237 # PHP4 or PHP5 without enabling exceptions
238 $obj =& new ADOdb_Active_Record('Products');
239 if ($obj->ErrorMsg()){
240 echo $obj->ErrorMsg();
241 } else {
242 $obj->Set($row);
243 }
244
245 # in PHP5, with exceptions enabled:
246
247 include('adodb-exceptions.inc.php');
248 try {
249 $obj =& new ADOdb_Active_Record('Products');
250 $obj->Set($row);
251 } catch(exceptions $e) {
252 echo $e->getMessage();
253 }
254 </pre>
255 <p>
256 <h3><li>Primary Keys</h3>
257 <p>
258 ADOdb_Active_Record does not require the table to have a primary key. You can insert records for such a table, but you will not be able to update nor delete.
259 <p>Sometimes you are retrieving data from a view or table that has no primary key, but has a unique index. You can dynamically set the primary key of a table through the constructor, or using ADOdb_Active_Record::SetPrimaryKeys():
260 <pre>
261 $pkeys = array('category','prodcode');
262
263 // set primary key using constructor
264 $rec = new ADOdb_Active_Record('Products', $pkeys);
265
266 // or use method
267 $rec->SetPrimaryKeys($pkeys);
268 </pre>
269
270
271 <h3><li>Retrieval of Auto-incrementing ID</h3>
272 When creating a new record, the retrieval of the last auto-incrementing ID is not reliable for databases that do not support the Insert_ID() function call (check $connection->hasInsertID). In this case we perform a <b>SELECT MAX($primarykey) FROM $table</b>, which will not work reliably in a multi-user environment. You can override the ADOdb_Active_Record::LastInsertID() function in this case.
273
274 <h3><li>Dealing with Multiple Databases</h3>
275 <p>
276 Sometimes we want to load data from one database and insert it into another using ActiveRecords. This can be done using the optional parameter of the ADOdb_Active_Record constructor. In the following example, we read data from db.table1 and store it in db2.table2:
277 <pre>
278 $db = NewADOConnection(...);
279 $db2 = NewADOConnection(...);
280
281 ADOdb_Active_Record::SetDatabaseAdapter($db2);
282
283 $activeRecs = $db->GetActiveRecords('table1');
284
285 foreach($activeRecs as $rec) {
286 $rec2 = new ADOdb_Active_Record('table2',$db2);
287 $rec2->id = $rec->id;
288 $rec2->name = $rec->name;
289
290 $rec2->Save();
291 }
292 </pre>
293 <p>
294 If you have to pass in a primary key called "id" and the 2nd db connection in the constructor, you can do so too:
295 <pre>
296 $rec = new ADOdb_Active_Record("table1",array("id"),$db2);
297 </pre>
298
299 <h3><li>$ADODB_ACTIVE_CACHESECS</h3>
300 <p>You can cache the table metadata (field names, types, and other info such primary keys) in $ADODB_CACHE_DIR (which defaults to /tmp) by setting
301 the global variable $ADODB_ACTIVE_CACHESECS to a value greater than 0. This will be the number of seconds to cache.
302 You should set this to a value of 30 seconds or greater for optimal performance.
303
304 <h3><li>Active Record Considered Bad?</h3>
305 <p>Although the Active Record concept is useful, you have to be aware of some pitfalls when using Active Record. The level of granularity of Active Record is individual records. It encourages code like the following, used to increase the price of all furniture products by 10%:
306 <pre>
307 $recs = $db->GetActiveRecords("Products","category='Furniture'");
308 foreach($recs as $rec) {
309 $rec->price *= 1.1; // increase price by 10% for all Furniture products
310 $rec->save();
311 }
312 </pre>
313 Of course a SELECT statement is superior because it's simpler and much more efficient (probably by a factor of x10 or more):
314 <pre>
315 $db->Execute("update Products set price = price * 1.1 where category='Furniture'");
316 </pre>
317 <p>Another issue is performance. For performance sensitive code, using direct SQL will always be faster than using Active Records due to overhead and the fact that all fields in a row are retrieved (rather than only the subset you need) whenever an Active Record is loaded.
318
319 <h3><li>Transactions</h3>
320 <p>
321 The default transaction mode in ADOdb is autocommit. So that is the default with active record too.
322 The general rules for managing transactions still apply. Active Record to the database is a set of insert/update/delete statements, and the db has no knowledge of active records.
323 <p>
324 Smart transactions, that does an auto-rollback if an error occurs, is still the best method to multiple activities (inserts/updates/deletes) that need to be treated as a single transaction:
325 <pre>
326 $conn->StartTrans();
327 $parent->save();
328 $child->save();
329 $conn->CompleteTrans();
330 </pre>
331
332 <h2>ADOConnection Supplement</h2>
333
334 <h3><li>ADOConnection::GetActiveRecords()</h3>
335 <p>
336 This allows you to retrieve an array of ADOdb_Active_Records. Returns false if an error occurs.
337 <pre>
338 $table = 'products';
339 $whereOrderBy = "name LIKE 'A%' ORDER BY Name";
340 $activeRecArr = $db->GetActiveRecords($table, $whereOrderBy);
341 foreach($activeRecArr as $rec) {
342 $rec->id = rand();
343 $rec->save();
344 }
345 </pre>
346 <p>
347 And to retrieve all records ordered by specific fields:
348 <pre>
349 $whereOrderBy = "1=1 ORDER BY Name";
350 $activeRecArr = $db->ADOdb_Active_Records($table);
351 </pre>
352 <p>
353 To use bind variables (assuming ? is the place-holder for your database):
354 <pre>
355 $activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
356 array('A%'));
357 </pre>
358 <p>You can also define the primary keys of the table by passing an array of field names:
359 <pre>
360 $activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
361 array('A%'), array('id'));
362 </pre>
363
364 <h3><li>ADOConnection::GetActiveRecordsClass()</h3>
365 <p>
366 This allows you to retrieve an array of objects derived from ADOdb_Active_Records. Returns false if an error occurs.
367 <pre>
368 class Product extends ADOdb_Active_Records{};
369 $table = 'products';
370 $whereOrderBy = "name LIKE 'A%' ORDER BY Name";
371 $activeRecArr = $db->GetActiveRecordsClass('Product',$table, $whereOrderBy);
372
373 # the objects in $activeRecArr are of class 'Product'
374 foreach($activeRecArr as $rec) {
375 $rec->id = rand();
376 $rec->save();
377 }
378 </pre>
379 <p>
380 To use bind variables (assuming ? is the place-holder for your database):
381 <pre>
382 $activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
383 array('A%'));
384 </pre>
385 <p>You can also define the primary keys of the table by passing an array of field names:
386 <pre>
387 $activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
388 array('A%'), array('id'));
389 </pre>
390
391 </ol>
392
393 <h2>Code Sample</h2>
394 <p>The following works with PHP4 and PHP5
395 <pre>
396 include('../adodb.inc.php');
397 include('../adodb-active-record.inc.php');
398
399 // uncomment the following if you want to test exceptions
400 #if (PHP_VERSION >= 5) include('../adodb-exceptions.inc.php');
401
402 $db = NewADOConnection('mysql://root@localhost/northwind');
403 $db->debug=1;
404 ADOdb_Active_Record::SetDatabaseAdapter($db);
405
406 $db->Execute("CREATE TEMPORARY TABLE `persons` (
407 `id` int(10) unsigned NOT NULL auto_increment,
408 `name_first` varchar(100) NOT NULL default '',
409 `name_last` varchar(100) NOT NULL default '',
410 `favorite_color` varchar(100) NOT NULL default '',
411 PRIMARY KEY (`id`)
412 ) ENGINE=MyISAM;
413 ");
414
415 class Person extends ADOdb_Active_Record{}
416 $person = new Person();
417
418 echo "&lt;p>Output of getAttributeNames: ";
419 var_dump($person->getAttributeNames());
420
421 /**
422 * Outputs the following:
423 * array(4) {
424 * [0]=>
425 * string(2) "id"
426 * [1]=>
427 * string(9) "name_first"
428 * [2]=>
429 * string(8) "name_last"
430 * [3]=>
431 * string(13) "favorite_color"
432 * }
433 */
434
435 $person = new Person();
436 $person->nameFirst = 'Andi';
437 $person->nameLast = 'Gutmans';
438 $person->save(); // this save() will fail on INSERT as favorite_color is a must fill...
439
440
441 $person = new Person();
442 $person->name_first = 'Andi';
443 $person->name_last = 'Gutmans';
444 $person->favorite_color = 'blue';
445 $person->save(); // this save will perform an INSERT successfully
446
447 echo "&lt;p>The Insert ID generated:"; print_r($person->id);
448
449 $person->favorite_color = 'red';
450 $person->save(); // this save() will perform an UPDATE
451
452 $person = new Person();
453 $person->name_first = 'John';
454 $person->name_last = 'Lim';
455 $person->favorite_color = 'lavender';
456 $person->save(); // this save will perform an INSERT successfully
457
458 // load record where id=2 into a new ADOdb_Active_Record
459 $person2 = new Person();
460 $person2->Load('id=2');
461 var_dump($person2);
462
463 // retrieve an array of records
464 $activeArr = $db->GetActiveRecordsClass($class = "Person",$table = "persons","id=".$db->Param(0),array(2));
465 $person2 =& $activeArr[0];
466 echo "&lt;p>Name first (should be John): ",$person->name_first, "&lt;br>Class = ",get_class($person2);
467 </pre>
468
469 <h3>Todo (Code Contributions welcome)</h3>
470 <p>Check _original and current field values before update, only update changes. Also if the primary key value is changed, then on update, we should save and use the original primary key values in the WHERE clause!
471 <p>Handle 1-to-many relationships.
472 <p>PHP5 specific: Make GetActiveRecords*() return an Iterator.
473 <p>PHP5 specific: Change PHP5 implementation of Active Record to use __get() and __set() for better performance.
474
475 <h3> Change Log</h3>
476 <p>0.03 <br>
477 - Now we only update fields that have changed, using $this->_original.<br>
478 - We do not include auto_increment fields in replace(). Thx Travis Cline<br>
479 - Added ADODB_ACTIVE_CACHESECS.<br>
480
481 <p>0.02 <br>
482 - Much better error handling. ErrorMsg() implemented. Throw implemented if adodb-exceptions.inc.php detected.<br>
483 - You can now define the primary keys of the view or table you are accessing manually.<br>
484 - The Active Record allows you to create an object which does not have a primary key. You can INSERT but not UPDATE in this case.
485 - Set() documented.<br>
486 - Fixed _pluralize bug with y suffix.
487
488 <p>
489 0.01 6 Mar 2006<br>
490 - Fixed handling of nulls when saving (it didn't save nulls, saved them as '').<br>
491 - Better error handling messages.<br>
492 - Factored out a new method GetPrimaryKeys().<br>
493 <p>
494 0.00 5 Mar 2006<br>
495 1st release
496 </body>
497 </html>