felixge / debuggable-scraps

MIT licensed code without warranty ; )

This URL has Read+Write access

felixge (author)
Thu Mar 05 18:09:24 -0800 2009
commit  3fbfca1bd3205e78aac80414bb8e8556a40496ae
tree    c1401d9d8598bd57ec310b1b608d394606ccc2ed
parent  70ca21000c1309128ef9e5b63b704761dc619f7b
debuggable-scraps / cakephp / behaviors / lookupable / lookupable.php
100644 47 lines (45 sloc) 1.284 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
<?php
/**
* A CakePHP behavior to easily look up the id's of records or create them if they do not exist yet. Useful when working with lots
* of lookup / status tables.
*
* Copyright 2008, Debuggable, Ltd.
* Hibiskusweg 26c
* 13089 Berlin, Germany
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2008, Debuggable, Ltd.
* @version 1.0
* @author Felix Geisendörfer <felix@debuggable.com>, Tim Koschützki <tim@debuggable.com>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class LookupableBehavior extends ModelBehavior {
function lookup(&$model, $conditions, $field = 'id', $create = true) {
if (!is_array($conditions)) {
$conditions = array ($model->displayField => $conditions);
}
 
if (!empty($field)) {
$fieldValue = $model->field($field, $conditions);
} else {
$fieldValue = $model->find($conditions);
}
if ($fieldValue !== false) {
return $fieldValue;
}
if (!$create) {
return false;
}
$model->create($conditions);
if (!$model->save()) {
return false;
}
$conditions[$model->primaryKey] = $model->id;
if (empty($field)) {
return $model->read();
}
return $model->field($field, $conditions);
}
}
 
?>