Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 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::Replace</h3>
188
<p>
189
ADOdb supports replace functionality, whereby the record is inserted if it does not exists, or updated otherwise.
190
<pre>
191
$rec = new ADOdb_Active_Record("product");
192
$rec->name = 'John';
193
$rec->tel_no = '34111145';
194
$ok = $rec->replace(); // 0=failure, 1=update, 2=insert
195
</pre>
196
 
197
 
198
<h3><li>ADOdb_Active_Record::Load()</h3>
199
<p>Sometimes, we want to load a single record into an Active Record. We can do so using:
200
<pre>
201
$person->load("id=3");
202
 
203
// or using bind parameters
204
 
205
$person->load("id=?", array(3));
206
</pre>
207
<p>Returns false if an error occurs.
208
 
209
<h3><li>Error Handling and Debugging</h3>
210
<p>
211
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. 
212
<p>
213
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:
214
<pre>
215
# right!
216
$ok = $rec->Save();
217
if (!$ok) $err = $rec->ErrorMsg();
218
 
219
# wrong :(
220
$rec->Save();
221
if ($rec->ErrorMsg()) echo "Wrong way to detect error";
222
</pre>
223
<p>The ADOConnection::Debug property is obeyed. So
224
if $db->debug is enabled, then ADOdb_Active_Record errors are also outputted to standard output and written to the browser.
225
 
226
<h3><li>ADOdb_Active_Record::Set()</h3>
227
<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.
228
<pre>
229
$row = $db->GetRow("select * from tablex where id=$id");
230
 
231
# PHP4 or PHP5 without enabling exceptions
232
$obj =& new ADOdb_Active_Record('Products');
233
if ($obj->ErrorMsg()){
234
	echo $obj->ErrorMsg();
235
} else {
236
	$obj->Set($row);
237
}
238
 
239
# in PHP5, with exceptions enabled:
240
 
241
include('adodb-exceptions.inc.php');
242
try {
243
	$obj =& new ADOdb_Active_Record('Products');
244
	$obj->Set($row);
245
} catch(exceptions $e) {
246
	echo $e->getMessage();
247
}
248
</pre>
249
<p>
250
<h3><li>Primary Keys</h3>
251
<p>
252
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. 
253
<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():
254
<pre>
255
	$pkeys = array('category','prodcode');
256
 
257
	// set primary key using constructor
258
	$rec = new ADOdb_Active_Record('Products', $pkeys);
259
 
260
	 // or use method
261
	$rec->SetPrimaryKeys($pkeys);
262
</pre>
263
<h3><li>Retrieval of Auto-incrementing ID</h3>
264
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.
265
 
266
<h3><li>Dealing with Multiple Databases</h3>
267
<p>
268
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:
269
<pre>
270
$db = NewADOConnection(...);
271
$db2 = NewADOConnection(...);
272
 
273
ADOdb_Active_Record::SetDatabaseAdapter($db2);
274
 
275
$activeRecs = $db->GetActiveRecords('table1');
276
 
277
foreach($activeRecs as $rec) {
278
	$rec2 = new ADOdb_Active_Record('table2',$db2);
279
	$rec2->id = $rec->id;
280
	$rec2->name = $rec->name;
281
 
282
	$rec2->Save();
283
}
284
</pre>
285
<p>
286
If you have to pass in a primary key called "id" and the 2nd db connection in the constructor, you can do so too:
287
<pre>
288
$rec = new ADOdb_Active_Record("table1",array("id"),$db2);
289
</pre>
290
 
291
<h3><li>Active Record Considered Bad?</h3>
292
<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%:
293
<pre>
294
 $recs = $db->GetActiveRecords("Products","category='Furniture'");
295
 foreach($recs as $rec) {
296
    $rec->price *= 1.1; // increase price by 10% for all Furniture products
297
    $rec->save();
298
 }
299
</pre>
300
Of course a SELECT statement is superior because it's simpler and much more efficient (probably by a factor of x10 or more):
301
<pre>
302
   $db->Execute("update Products set price = price * 1.1 where category='Furniture'");
303
</pre>
304
<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.
305
 
306
 
307
<h2>ADOConnection Supplement</h2>
308
 
309
<h3><li>ADOConnection::GetActiveRecords()</h3>
310
<p>
311
This allows you to retrieve an array of ADOdb_Active_Records. Returns false if an error occurs.
312
<pre>
313
$table = 'products';
314
$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
315
$activeRecArr = $db->GetActiveRecords($table, $whereOrderBy);
316
foreach($activeRecArr as $rec) {
317
	$rec->id = rand();
318
	$rec->save();
319
}
320
</pre>
321
<p>
322
And to retrieve all records ordered by specific fields:
323
<pre>
324
$whereOrderBy = "1=1 ORDER BY Name";
325
$activeRecArr = $db->ADOdb_Active_Records($table);
326
</pre>
327
<p>
328
To use bind variables (assuming ? is the place-holder for your database):
329
<pre>
330
$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
331
						array('A%'));
332
</pre>
333
<p>You can also define the primary keys of the table by passing an array of field names:
334
<pre>
335
$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
336
						array('A%'), array('id'));
337
</pre>
338
 
339
<h3><li>ADOConnection::GetActiveRecordsClass()</h3>
340
<p>
341
This allows you to retrieve an array of objects derived from ADOdb_Active_Records. Returns false if an error occurs.
342
<pre>
343
class Product extends ADOdb_Active_Records{};
344
$table = 'products';
345
$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
346
$activeRecArr = $db->GetActiveRecordsClass('Product',$table, $whereOrderBy);
347
 
348
# the objects in $activeRecArr are of class 'Product'
349
foreach($activeRecArr as $rec) {
350
	$rec->id = rand();
351
	$rec->save();
352
}
353
</pre>
354
<p>
355
To use bind variables (assuming ? is the place-holder for your database):
356
<pre>
357
$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
358
						array('A%'));
359
</pre>
360
<p>You can also define the primary keys of the table by passing an array of field names:
361
<pre>
362
$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
363
						array('A%'), array('id'));
364
</pre>
365
 
366
</ol>
367
 
368
<h2>Code Sample</h2>
369
<p>The following works with PHP4 and PHP5
370
<pre>
371
include('../adodb.inc.php');
372
include('../adodb-active-record.inc.php');
373
 
374
// uncomment the following if you want to test exceptions
375
#if (PHP_VERSION >= 5) include('../adodb-exceptions.inc.php');
376
 
377
$db = NewADOConnection('mysql://root@localhost/northwind');
378
$db->debug=1;
379
ADOdb_Active_Record::SetDatabaseAdapter($db);
380
 
381
$db->Execute("CREATE TEMPORARY TABLE `persons` (
382
                `id` int(10) unsigned NOT NULL auto_increment,
383
                `name_first` varchar(100) NOT NULL default '',
384
                `name_last` varchar(100) NOT NULL default '',
385
                `favorite_color` varchar(100) NOT NULL default '',
386
                PRIMARY KEY  (`id`)
387
            ) ENGINE=MyISAM;
388
           ");
389
 
390
class Person extends ADOdb_Active_Record{}
391
$person = new Person();
392
 
393
echo "&lt;p>Output of getAttributeNames: ";
394
var_dump($person->getAttributeNames());
395
 
396
/**
397
 * Outputs the following:
398
 * array(4) {
399
 *    [0]=>
400
 *    string(2) "id"
401
 *    [1]=>
402
 *    string(9) "name_first"
403
 *    [2]=>
404
 *    string(8) "name_last"
405
 *    [3]=>
406
 *    string(13) "favorite_color"
407
 *  }
408
 */
409
 
410
$person = new Person();
411
$person->nameFirst = 'Andi';
412
$person->nameLast  = 'Gutmans';
413
$person->save(); // this save() will fail on INSERT as favorite_color is a must fill...
414
 
415
 
416
$person = new Person();
417
$person->name_first     = 'Andi';
418
$person->name_last      = 'Gutmans';
419
$person->favorite_color = 'blue';
420
$person->save(); // this save will perform an INSERT successfully
421
 
422
echo "&lt;p>The Insert ID generated:"; print_r($person->id);
423
 
424
$person->favorite_color = 'red';
425
$person->save(); // this save() will perform an UPDATE
426
 
427
$person = new Person();
428
$person->name_first     = 'John';
429
$person->name_last      = 'Lim';
430
$person->favorite_color = 'lavender';
431
$person->save(); // this save will perform an INSERT successfully
432
 
433
// load record where id=2 into a new ADOdb_Active_Record
434
$person2 = new Person();
435
$person2->Load('id=2');
436
var_dump($person2);
437
 
438
// retrieve an array of records
439
$activeArr = $db->GetActiveRecordsClass($class = "Person",$table = "persons","id=".$db->Param(0),array(2));
440
$person2 =& $activeArr[0];
441
echo "&lt;p>Name first (should be John): ",$person->name_first, "&lt;br>Class = ",get_class($person2);	
442
</pre>
443
 
444
 <h3>Todo (Code Contributions welcome)</h3>
445
 <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!
446
 <p>Handle 1-to-many relationships.
447
 <p>PHP5 specific:  Make GetActiveRecords*() return an Iterator.
448
 <p>PHP5 specific: Change PHP5 implementation of Active Record to use __get() and __set() for better performance.
449
 
450
<h3> Change Log</h3>
451
<p>0.02 <br>
452
- Much better error handling. ErrorMsg() implemented. Throw implemented if adodb-exceptions.inc.php detected.<br>
453
- You can now define the primary keys of the view or table you are accessing manually.<br>
454
- 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.
455
- Set() documented.<br>
456
- Fixed _pluralize bug with y suffix.
457
 
458
<p>
459
 0.01 6 Mar 2006<br>
460
- Fixed handling of nulls when saving (it didn't save nulls, saved them as '').<br>
461
- Better error handling messages.<br>
462
- Factored out a new method GetPrimaryKeys().<br>
463
 <p>
464
 0.00 5 Mar 2006<br>
465
 1st release
466
</body>
467
</html>