My favorites | Sign in
Project Home
Checkout   Browse   Changes    
 
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
<?php
/**
* A generic table gateway.
*/
class pdoext_TableGateway implements IteratorAggregate, Countable {
protected $tablename;
protected $pkey = -1;

protected $db;
protected $columns = null;

/**
*
* @param $tablename string Name of the table
* @param $db pdoext_Connection The database connection
*/
function __construct($tablename, pdoext_Connection $db) {
$this->tablename = $tablename;
$this->db = $db;
}

function getIterator() {
return $this->select();
}

/**
* Creates a selection query.
*/
function selectPaginated($current_page = 1, $page_size = 10) {
return new pdoext_PaginatedSelection($this, $this->db, $current_page, $page_size);
}

protected function marshal($object) {
if (is_array($object)) {
return $object;
}
if (is_object($object)) {
if (method_exists($object, 'getArrayCopy')) {
return $object->getArrayCopy();
}
return get_object_vars($object);
}
throw new Exception("Unable to marshal input into hash.");
}

/**
* Introspects the schema, and returns an array of the table's columns.
* @return [] hash
*/
function reflect() {
if (!$this->columns) {
$this->columns = $this->db->getTableMeta($this->tablename);
}
return $this->columns;
}

/**
* Returns the PK column.
* Note that this pre-supposes that the primary key is a single column, which may not always be the case.
* @return mixed
*/
function getPKey() {
if ($this->pkey === -1) {
$this->pkey = $this->_getPKey();
}
return $this->pkey;
}

protected function _getPKey() {
foreach ($this->reflect() as $column => $info) {
if ($info['pk']) {
return $column;
}
}
}

/**
* @return string
*/
function getTable() {
return $this->tablename;
}

/**
* Returns the column names
* @return [] string
*/
function getColumns() {
return array_keys($this->reflect());
}

/**
* Returns the column names of all columns that aren't TEXT/BLOB's
* @return [] string
*/
function getListableColumns() {
$columns = array();
foreach ($this->reflect() as $column => $info) {
if (!$info['blob']) {
$columns[] = $column;
}
}
return $columns;
}

/**
* Resets errors for an entity.
* You can override this, if you want to report errors in a different way.
*/
protected function clearErrors($entity) {
if (is_object($entity)) {
$entity->errors = array();
}
}

/**
* Determines if there are any errors for an entity.
* You can override this, if you want to report errors in a different way.
*/
protected function hasErrors($entity) {
return is_object($entity) && is_array($entity->errors) && count($entity->errors) > 0;
}

/**
* Hook for validating before update or insert
* Set errors on `$data->errors` to abort.
*/
protected function validate($data) {}

/**
* Hook for validating before update.
* Set errors on `$data->errors` to abort.
*/
protected function validateUpdate($data) {}

/**
* Hook for validating before insert
* Set errors on `$data->errors` to abort.
*/
protected function validateInsert($data) {}

/**
* Selects a single row from the table.
* If multiple rows are matched, only the first result is returned.
* @param $condition array Associative array of column => value to serve as conditions for the query.
* @return array
*/
function fetch($condition) {
$condition = $this->marshal($condition);
$query = "SELECT * FROM " . $this->db->quoteName($this->tablename);
$where = array();
$bind = array();
foreach ($condition as $column => $value) {
if ($value instanceOf pdoext_query_iExpression) {
$where[] = $this->db->quoteName($column) . " = " . $value->toSql($this->db);
} else {
$where[] = $this->db->quoteName($column) . " = :" . $column;
$bind[":" . $column] = $value;
}
}
if (count($where) === 0) {
throw new Exception("No conditions given for fetch");
}
$query .= "\nWHERE\n " . implode("\n AND ", $where);
$result = $this->db->pexecute($query, $bind);
if (method_exists($this, 'load')) {
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row ? $this->load($row) : null;
}
return $result->fetch(PDO::FETCH_ASSOC);
}

/**
* Return a selection of all records
*/
function select($limit = null, $offset = 0, $order = null, $direction = null) {
$query = "SELECT * FROM " . $this->db->quoteName($this->tablename);
if ($order) {
$query .= "\nORDER BY " . $this->db->quoteName($order);
if ($direction) {
$query .= strtolower($direction) === 'desc' ? 'desc' : 'asc';
}
}
if ($limit) {
$query .= "\nLIMIT " . ((integer) $limit);
}
if ($offset) {
$query .= "\nOFFSET " . ((integer) $offset);
}
$result = $this->db->query($query);
$result->setFetchMode(PDO::FETCH_ASSOC);
if (method_exists($this, 'load')) {
return new pdoext_Resultset($result, $this);
// TODO: Replace with a lazy iterator, to take benefit of buffered queries
// return new ArrayIterator(array_map(array($this, 'load'), $result->fetchAll(PDO::FETCH_ASSOC)));
}
return $result;
}

/**
* Return a count of all records
*/
function count() {
$query = "SELECT count(*) FROM " . $this->db->quoteName($this->tablename);
$result = $this->db->query($query);
$row = $result->fetch(PDO::FETCH_NUM);
return $row[0];
}

/**
* Inserts a row to the table.
* @param $data array Associative array of column => value to insert.
* @return boolean
*/
function insert($entity) {
$this->clearErrors($entity);
$this->validateInsert($entity);
$this->validate($entity);
if ($this->hasErrors($entity)) {
return null;
}
$data = $this->marshal($entity);
$query = "INSERT INTO " . $this->db->quoteName($this->tablename);
$columns = array();
$values = array();
$bind = array();
foreach ($this->getColumns() as $column) {
if (array_key_exists($column, $data)) {
$value = $data[$column];
$columns[] = $this->db->quoteName($column);
if ($value instanceOf pdoext_query_iExpression) {
$values[] = $value->toSql($this->db);
} else {
$values[] = ":" . $column;
$bind[":" . $column] = $value;
}
}
}
$query .= " (" . implode(", ", $columns) . ")";
$query .= " VALUES (" . implode(", ", $values) . ")";
$this->db->pexecute($query, $bind);
return $this->db->lastInsertId();
}

/**
* Updates one or more rows.
* If second parameter isn't set, the PK from first parameter is used instead.
* @param $data array Associative array of column => value to update the found columns with.
* @param $condition array Associative array of column => value to serve as conditions for the query.
* @return boolean
*/
function update($entity, $condition = null) {
$this->clearErrors($entity);
$this->validateUpdate($entity);
$this->validate($entity);
if ($this->hasErrors($entity)) {
return false;
}
$data = $this->marshal($entity);
$pk = $this->getPKey();
if (!is_null($condition)) {
$condition = $this->marshal($condition);
} elseif (isset($data[$pk])) {
$condition = array($pk => $data[$pk]);
} else {
throw new Exception("No conditions given and PK is missing for update");
}
$query = "UPDATE " . $this->db->quoteName($this->tablename) . "\nSET";
$columns = array();
$bind = array();
foreach ($this->getColumns() as $column) {
if (array_key_exists($column, $data) && $column != $pk) {
$value = $data[$column];
if ($value instanceOf pdoext_query_iExpression) {
$columns[] = $this->db->quoteName($column) . " = " . $value->toSql($this->db);
} else {
$columns[] = $this->db->quoteName($column) . " = :" . $column;
$bind[":" . $column] = $value;
}
}
}
$query .= "\n " . implode(",\n ", $columns);
$where = array();
foreach ($condition as $column => $value) {
if ($value instanceOf pdoext_query_iExpression) {
$where[] = $this->db->quoteName($column) . " = :where_" . $value->toSql($this->db);
} else {
$where[] = $this->db->quoteName($column) . " = :where_" . $column;
$bind[":where_" . $column] = $value;
}
}
if (count($where) === 0) {
throw new Exception("No conditions given for update");
}
$query .= "\nWHERE\n " . implode("\n AND ", $where);
return $this->db->pexecute($query, $bind);
}

/**
* Deletes one or more rows.
* @param $condition array Associative array of column => value to serve as conditions for the query.
* @return boolean
*/
function delete($condition) {
$condition = $this->marshal($condition);
$query = "DELETE FROM " . $this->db->quoteName($this->tablename);
$where = array();
$bind = array();
foreach ($condition as $column => $value) {
if ($value instanceOf pdoext_query_iExpression) {
$where[] = $this->db->quoteName($column) . " = " . $value->toSql($this->db);
} else {
$where[] = $this->db->quoteName($column) . " = :" . $column;
$bind[":" . $column] = $value;
}
}
if (count($where) === 0) {
throw new Exception("No conditions given for delete");
}
$query .= "\nWHERE\n " . implode("\n AND ", $where);
$result = $this->db->pexecute($query, $bind);
return $result->rowCount() > 0;
}
}

class pdoext_Resultset implements Iterator {
protected $cursor;
protected $loader;
protected $key = 0;
protected $current = null;
function __construct($cursor, $loader) {
$this->cursor = $cursor;
$this->loader = $loader;
}
protected function load($row) {
return $row ? $this->loader->load($row) : $row;
}
function current() {
return $this->current = $this->current === null ? $this->load($this->cursor->fetch(PDO::FETCH_ASSOC)) : $this->current;
}
function key() {
return $this->key;
}
function next() {
$this->key++;
$this->current = null;
return $this->current();
}
function rewind() {
if ($this->current !== null) {
throw new Exception("Can't rewind database resultset");
}
}
function valid() {
return $this->current() !== false;
}
}

class pdoext_PaginatedSelection extends pdoext_Query implements IteratorAggregate, Countable {
protected $db;
protected $gateway;
protected $result;
protected $total_count;
function __construct(pdoext_TableGateway $gateway, pdoext_Connection $db, $current_page, $page_size = 10) {
parent::__construct($gateway->getTable());
$this->gateway = $gateway;
$this->db = $db;
$this->setSqlCalcFoundRows();
$this->setLimit($page_size);
$this->setOffset(max($current_page - 1, 0) * $page_size);
}
function count() {
$this->executeQuery();
return $this->total_count;
}
function getIterator() {
$this->executeQuery();
return $this->result;
}
protected function executeQuery() {
if (!$this->result) {
$result = $this->db->query($this);
$result->setFetchMode(PDO::FETCH_ASSOC);
if (method_exists($this->gateway, 'load')) {
$this->result = new pdoext_Resultset($result, $this->gateway);
} else {
$this->result = $result;
}
$result = $this->db->query("SELECT FOUND_ROWS()");
$row = $result->fetch();
$this->total_count = $row[0];
}
}
}

Change log

r46 by troelskn on Dec 26, 2009   Diff
range check on page offset
Go to: 
Project members, sign in to write a code review

Older revisions

r45 by troelskn on Dec 26, 2009   Diff
Added paginated selection wrapper to
tablegateway
r44 by troelskn on Dec 25, 2009   Diff
Fixed code-style + moved check for
is_object into aux methods to allow
better customisation.
r43 by troelskn on Dec 25, 2009   Diff
Fixes  issue #12 
All revisions of this file

File info

Size: 11740 bytes, 394 lines
Powered by Google Project Hosting