public
Description: Database abstraction layer in PHP5
Homepage:
Clone URL: git://github.com/foobarbazquux/daonut.git
daonut / dynamicdao.inc.php
100644 94 lines (81 sloc) 2.339 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
<?php
/**
* @author Karen Ziv <karen@perlessence.com>
* @see http://github.com/foobarbazquux/daonut/wikis/dynamicdao
**/
class DynamicDao {
    
    public $db;
    public $table;
    public $fields = array();
 
    public $connector;
    protected $querybuilder;
    protected $sql;
    
    /**
* Stores a database connector
**/
    public function setConnector(Connector $connector) {
        if (!$connector instanceof Connector) {
            return FALSE;
        }
        $this->connector = $connector;
    }
 
    public function setQueryBuilder(QueryBuilder $qb) {
        $this->querybuilder = $qb;
    }
    
    /**
* Stores a SQL query string for execution
* @param {str} query string
* @return {bool} String passes basic validation or not
**/
    public function query($sql) {
        if (empty($sql)) {
            return FALSE;
        }
        $this->sql = $sql;
        return TRUE;
    }
 
    public function sql() {
        return $this->sql;
    }
    
    /**
* Executes a query
* @param {bool}
**/
    public function execute($pre_validate = TRUE) {
        if (empty($this->connector)) {
            return FALSE;
        }
        if ($this->querybuilder) {
            try {
                $this->sql = $this->querybuilder->build();
            }
            catch (QueryBuilderException $e) {
                return FALSE;
            }
        }
        return empty($this->sql)
            ? FALSE
            : $this->connector->query($this->sql);
    }
 
    /**
* Magic field doohickey
* @param {str} Name of method
**/
    public function __call($m, $a) {
 
        if (method_exists($this->connector, $m)) {
            return call_user_func_array(array($this->connector, $m), $a);
        }
        elseif ($this->querybuilder) { // Everything defaults to run against QueryBuilder if it exists
            try {
                return call_user_func_array(array($this->querybuilder, $m), $a);
            }
            catch (QueryBuilderException $e) {
                throw new DynamicDaoException("Method '$m' does not exist: " . $e->getMessage());
            }
        }
        else {
            throw new DynamicDaoException("Method '$m' does not exist.");
        }
 
    }
    
}
 
class DynamicDaoException extends Exception {}