public
Description: Git mirror of the CMS Made Simple 2.0 rewrite
Homepage: http://cmsmadesimple.org
Clone URL: git://github.com/tedkulp/cmsmadesimple-2-0.git
cmsmadesimple-2-0 / lib / classes / class.cms_object_relational_mapping.php
100644 463 lines (383 sloc) 12.223 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
<?php
#CMS - CMS Made Simple
#(c)2004-6 by Ted Kulp (ted@cmsmadesimple.org)
#This project's homepage is: http://cmsmadesimple.org
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#BUT withOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#$Id$
 
debug_buffer('', 'Start Loading ORM');
 
class CmsObjectRelationalMappting extends Overloader
{
  /**
   * Used to define any default settings for this object. Not
   * all fields need to be defined, as they'll come out of the
   * database field names anyway.
   */
  var $params = array();
 
  /**
   * Used to define a variation between a database field and
   * what the property name should be. Takes a hash of
   * 'database field name' => 'property name'
   */
  var $field_maps = array();
  
  /**
   * Used to define a different table name for this object if it
   * doesn't match the predetermined name based on the object's class
   * name.
   */
  var $table = '';
  
  /**
   * Used to define an alternate field for the id. This basically says
   * whether or not we insert or update.
   */
  var $id_field = 'id';
  
  /**
   * Used to define a sequence to use for creating a new id to use. If
   * blank, then the auto increment for the database is used for the id.
   */
  var $sequence = '';
  
  /**
   * Used to define which field holds the record create date.
   */
  var $create_date_field = 'create_date';
  
  /**
   * Used to define which field holds the record modified date.
   */
  var $modified_date_field = 'modified_date';
  
  function __construct()
  {
    parent::__construct();
  }
  
  function register_orm_class($classname)
  {
    global $gCms;
    $ormclasses =& $gCms->orm;
    
    $name = underscore($classname);
    $ormclasses->$name = new $classname;
  }
  
  // Getter
  function _get($n, &$v)
  {
    $v = $this->params[$n];
    return true;
  }
 
  // Setter
  function _set($n, $val)
  {
    if (array_key_exists($n, $this->field_maps)) $n = $this->field_maps[$n];
    $this->params[$n] = $val;
    return true;
  }
  
  // Caller, applied when $function isn't defined
  function _call($function, $arguments, &$return)
  {
    if (startswith($function, 'find_by_'))
    {
      $return = $this->find_by_($function, $arguments);
    }
    else if (startswith($function, 'find_all_by_'))
    {
      $return = $this->find_all_by_($function, $arguments);
    }
  }
  
  /**
   * Method for handling the dynamic find_by_* functionality. It basically figures out
   * what field is being searched for and creates a query based on that field.
   *
   * @param $function The name of the function that came into the __call method
   * @param $arguments The arguments that came into the __call method
   *
   * @return The results of the find
   */
  function find_by_($function, $arguments)
  {
    $field = str_replace('find_by_', '', $function);
    
    //Figure out if we need to replace the field from the field mappings
    $new_map = array_flip($this->field_maps); //Flip the keys, since this is the reverse operation
    if (array_key_exists($field, $new_map)) $field = $new_map[$field];
    
    return $this->find(array('conditions' => array($field . ' = ?', array($arguments[0]))));
  }
  
  /**
   * Method for handling the dynamic find_all_by_* functionality. It basically figures out
   * what field is being searched for and creates a query based on that field.
   *
   * @param $function The name of the function that came into the __call method
   * @param $arguments The arguments that came into the __call method
   *
   * @return The results of the find_all
   */
  function find_all_by_($function, $arguments)
  {
    var_dump('function');
    $field = str_replace('find_all_by_', '', $function);
    
    //Figure out if we need to replace the field from the field mappings
    $new_map = array_flip($this->field_maps); //Flip the keys, since this is the reverse operation
    if (array_key_exists($field, $new_map)) $field = $new_map[$field];
    
    return $this->find_all(array('conditions' => array($field . ' = ?', array($arguments[0]))));
  }
  
  /**
   * Figures out the proper name of the table that's persisting this class.
   *
   * @return Name of the table to use
   */
  function get_table()
  {
    $classname = get_class($this);
    $table = $this->table != '' ? cms_db_prefix() . $this->table : cms_db_prefix() . strtolower($classname);
 
    return $table;
  }
  
  function find($arguments)
  {
    $table = $this->get_table();
    
    $query = '';
    $queryparams = array();
    
    list($query, $queryparams) = $this->generate_select_query_and_parameters($table, $arguments, $query, $queryparams);
    
    return $this->find_by_query($query, $queryparams);
  }
  
  function find_by_query($query, $queryparams = array())
  {
    global $gCms;
    $db =& $gCms->GetDb();
    
    $classname = get_class($this);
 
    $row =& $db->GetRow($query, $queryparams);
 
    if($row)
    {
      $oneobj =& new $classname;
      $oneobj = $this->fill_object($row, $oneobj);
      return $oneobj;
    }
 
    return FALSE;
  }
  
  function find_all($arguments)
  {
    $table = $this->get_table();
    
    $query = '';
    $queryparams = array();
    
    list($query, $queryparams) = $this->generate_select_query_and_parameters($table, $arguments, $query, $queryparams);
    
    return $this->find_all_by_query($query, $queryparams);
  }
  
  function find_all_by_query($query, $queryparams = array())
  {
    global $gCms;
    $db =& $gCms->GetDb();
    
    $classname = get_class($this);
 
    $result = array();
    $dbresult = &$db->Execute($query, $queryparams);
 
    while ($dbresult && !$dbresult->EOF)
    {
      $oneobj =& new $classname;
      $oneobj = $this->fill_object($dbresult->fields, $oneobj);
      $result[] =& $oneobj;
      $dbresult->MoveNext();
    }
    
    return $result;
  }
  
  function save()
  {
    global $gCms;
    $db =& $gCms->GetDb();
 
    $table = $this->get_table();
 
    $id_field = $this->id_field;
    $id = $this->$id_field;
    
    //Figure out if we need to replace the field from the field mappings
    $new_map = array_flip($this->field_maps); //Flip the keys, since this is the reverse operation
    if (array_key_exists($id_field, $new_map)) $id_field = $new_map[$id_field];
    
    $fields = $this->get_columns_in_table();
    
    $time = $db->DBTimeStamp(time());
    
    //If we have an id, so an update.
    //If not, do an insert.
    if (isset($id) && $id > 0)
    {
      $query = 'UPDATE ' . $table . ' SET ';
      $midpart = '';
      $queryparams = array();
 
      foreach($fields as $onefield)
      {
        $localname = $onefield;
        if (array_key_exists($localname, $this->field_maps)) $localname = $this->field_maps[$localname];
        if ($onefield == $this->modified_date_field)
        {
          #$queryparams[] = $time;
          $midpart .= $onefield . ' = ' . $time . ', ';
          $this->$onefield = time();
        }
        else if (array_key_exists($localname, $this->params))
        {
          $queryparams[] = $this->params[$localname];
          $midpart .= $onefield . ' = ?, ';
        }
      }
      
      if ($midpart != '')
      {  
        $midpart = substr($midpart, 0, -2);
        $query .= $midpart . ' WHERE ' . $id_field . ' = ?';
        $queryparams[] = $id;
      }
      
      return $db->Execute($query, $queryparams);
    }
    else
    {
      $new_id = -1;
      if ($this->sequence != '')
      {
        $new_id = $db->GenID(cms_db_prefix() . $this->sequence);
        $this->$id_field = $new_id;
      }
 
      $query = 'INSERT INTO ' . $table . ' (';
      $midpart = '';
      $queryparams = array();
      
      foreach($fields as $onefield)
      {
        $localname = $onefield;
        if (array_key_exists($localname, $this->field_maps)) $localname = $this->field_maps[$localname];
        
        if ($onefield == $this->create_date_field || $onefield == $this->modified_date_field)
        {
          $queryparams[] = trim($time, "'");
          $midpart .= $onefield . ', ';
          $this->$onefield = time();
        }
        else if (array_key_exists($localname, $this->params))
        {
          if (!($new_id == -1 && $localname == $this->$id_field))
          {
            $queryparams[] = $this->params[$localname];
            $midpart .= $onefield . ', ';
          }
        }
      }
      
      if ($midpart != '')
      {
        $midpart = substr($midpart, 0, -2);
        $query .= $midpart . ') VALUES (';
        $query .= implode(',', array_fill(0, count($queryparams), '?'));
        $query .= ')';
      }
      
      $result = $db->Execute($query, $queryparams);
      
      if ($new_id == -1)
      {
        $new_id = $db->Insert_ID();
        $this->$id_field = $new_id;
      }
      
      return $result;
    }
  }
  
  /**
   * Deletes a record from the table that persists this class. If no id is given, then
   * it deletes the object given. If an id is given, then it deletes that one from the
   * database directly.
   *
   * @param $id The id to delete. If none, then deletes the object called on.
   *
   * @return Boolean based on whether or not the delete was successful.
   */
  function delete($id = -1)
  {
    global $gCms;
    $db =& $gCms->GetDb();
 
    if ($id == -1)
      $id = $this->$id;
      
    $table = $this->get_table();
    $id_field = $this->id_field;
    
    //Figure out if we need to replace the field from the field mappings
    $new_map = array_flip($this->field_maps); //Flip the keys, since this is the reverse operation
    if (array_key_exists($id_field, $new_map)) $id_field = $new_map[$id_field];
 
    return $db->Execute('DELETE FROM ' . $table . ' WHERE ' . $id_field . ' = ' . $id);
  }
  
  /**
   * Fills an object with the fields from the database.
   *
   * @param &$resulthash Reference to the has for this record that came from the database
   * @param &$object Reference to the object we should fill
   *
   * @return The object we filled (php4 doesn't seem to handle the reference right)
   */
  function fill_object(&$resulthash, &$object)
  {
    foreach ($resulthash as $k=>$v)
    {
      $object->$k = $v;
    }
 
    return $object;
  }
  
  /**
   * Generates a select query based on the arguments sent to the find and find_by
   * methods.
   *
   * @param $table Name of the table that should be SELECT'd from
   * @param $arguments Arguments passed to the find and find_by methods
   * @param &$query Reference to the query string that will be modified by this method
   * @param &$queryparams Reference to the array of query params passed on to adodb
   *
   * @return An array of $query and $queryparams
   */
  function generate_select_query_and_parameters($table, $arguments, $query, $queryparams)
  {
    $query = "SELECT * FROM " . $table;
    if (array_key_exists('conditions', $arguments))
    {
      $query .= ' WHERE ' . $arguments['conditions'][0];
      if (isset($arguments['conditions'][1]) && is_array($arguments['conditions'][1]))
      {
        $queryparams = array_merge($queryparams, $arguments['conditions'][1]);
      }
    }
    if (array_key_exists('order', $arguments))
    {
      $query .= ' ORDER BY ' . $arguments['order'];
    }
    
    return array($query, $queryparams);
  }
  
  /**
   * Generates an array of column names in the table that perists this class.
   *
   * @return An array of column names
   */
  function get_columns_in_table()
  {
    $cache = $this->_getDescriptionCache();
    if ($cache !== FALSE)
      return $cache;
 
    global $gCms;
    $config =& $gCms->GetConfig();
 
    $dbms = $gCms->config['dbms'];
    if ($dbms == 'mysqli') $dbms = 'mysql';
 
    include_once(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'dbo' . DIRECTORY_SEPARATOR . $dbms . '.get_columns_in_table.php');
    
    $fields = dbo_get_columns_in_table($this);
    
    $this->_cacheDescription($fields);
    return $fields;
  }
  
  function _cacheDescription($fields)
  {
    global $gCms;
    $cache =& $gCms->desccache;
    
    $cache[$this->get_table()] =& $fields;
  }
  
  function _getDescriptionCache()
  {
    global $gCms;
    $cache =& $gCms->desccache;
    
    if (isset($cache[$this->get_table()]))
    {
      return $cache[$this->get_table()];
    }
 
    return FALSE;
  }
}
 
if (function_exists("overload") && phpversion() < 5)
{
   overload("CmsObjectRelationalMappting");
}
 
debug_buffer('', 'End Loading ORM');
 
?>