Subversion Repositories PHPX

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
27 PointedEar 1
<?php
2
 
3
require_once 'lib/Model.php';
4
 
5
abstract class Adapter
6
{
7
  /**
8
   * Database used by the adapter
9
   * @var Database
10
   */
11
  protected $_database = null;
12
 
13
  /**
14
   * Constructs the adapter, associating a {@link Database} with it
15
   * @param Database $database
16
   */
17
  /* Singleton */
18
  protected function __construct(Database $database)
19
  {
20
    $this->_database = $database;
21
  }
22
 
23
  /**
24
  * Selects data from one or more tables
25
  *
26
  * @return array
27
  * @see Database::select()
28
  */
29
  public function select($table, $columns = null, $where = null, $order = null, $limit = null)
30
  {
31
    return $this->_database->select($table, $columns, $where, $order, $limit);
32
  }
33
 
34
  /**
35
   * Finds all records matching the set properties of a model object
36
   *
37
   * @param Model $object
38
   * @return array[Model]
39
   */
40
  public function findAll(Model $object, $order = null, $limit = null)
41
  {
42
    $properties = $object->getPropertyVars();
43
    $where = array();
44
 
45
    foreach ($properties as $property)
46
    {
47
      if (!is_null($object->$property))
48
      {
49
        $where[$property] = $object->$property;
50
      }
51
    }
52
 
53
    $class = get_class($object);
54
    $query_result = $this->select($class::persistentTable, null, $where, $order, $limit);
55
 
56
    $num_results = count($query_result);
57
    if ($num_results === 0)
58
    {
59
      return null;
60
    }
61
 
62
    $result = array();
63
 
64
    foreach ($query_result as $row)
65
    {
66
      $result[] = new $class($row);
67
    }
68
 
69
    return $result;
70
  }
71
 
72
  /**
73
   * Finds the record for a model object by its primary key
74
   *
75
   * @param Model $object
76
   * @return Model
77
   *   The filled object if the primary key value could be found,
78
   *   <code>null</code> otherwise
79
   */
80
  public function find(Model $object)
81
  {
82
    $class = get_class($object);
83
    $primaryKey = $class::persistentPrimaryKey;
84
 
85
    if (is_array($primaryKey))
86
    {
87
      /* TODO */
88
    }
89
 
90
    $result = $this->select($class::persistentTable, null, array($primaryKey => $object->$primaryKey));
91
    if (0 == count($result))
92
    {
93
      return null;
94
    }
95
 
96
    $row = $result[0];
97
    $object->map($row);
98
 
99
    return $object;
100
  }
101
}