1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21:
22:
23: namespace picon;
24:
25: 26: 27: 28: 29: 30: 31:
32: class DataBaseTemplate implements DataBaseOperations
33: {
34: private $source;
35: private $driver;
36:
37: public function __construct(DataSource $source)
38: {
39: $this->source = $source;
40: $this->driver = $source->getDriver();
41: }
42:
43: public function getConnection()
44: {
45: return $this->source->getConnection();
46: }
47:
48: public function getDataSource()
49: {
50: return $this->source;
51: }
52:
53: public function __destruct()
54: {
55: $this->driver->dissconnect($this->getConnection());
56: }
57:
58: public function execute($sql)
59: {
60: $this->driver->query($sql, $this->getConnection());
61: }
62:
63: public function query($sql, RowMapper $mapper, $arguments = null)
64: {
65: $records = array();
66: $sql = $this->prepareArgs($sql, $arguments);
67: $results = $this->driver->query($sql, $this->getConnection());
68:
69: while($row = $this->driver->resultSetObject($results))
70: {
71: $record = $mapper->mapRow($row);
72: Args::notNull($record, 'row mapper return value');
73: array_push($records, $record);
74: }
75: return $records;
76: }
77:
78: public function update($sql, $arguments = null)
79: {
80: $sql = $this->prepareArgs($sql, $arguments);
81: $this->driver->query($sql, $this->getConnection());
82: return $this->driver->getAffectedRows($this->getConnection());
83: }
84:
85: public function insert($sql, $arguments = null)
86: {
87: $sql = $this->prepareArgs($sql, $arguments);
88: $this->driver->query($sql, $this->getConnection());
89: return $this->driver->getInsertedId($this->getConnection());
90: }
91:
92: private function prepareArgs($sql, $arguments = null)
93: {
94: if($arguments!=null && count($arguments)>0)
95: {
96: $sprintfargs = array_merge(array($sql), $arguments);
97: $sprintf = new \ReflectionFunction('sprintf');
98: $sql = $sprintf->invokeArgs($sprintfargs);
99: }
100: return $sql;
101: }
102:
103: public function queryForInt($sql, $arguments = null)
104: {
105: $sql = $this->prepareArgs($sql, $arguments);
106: $int = null;
107: $results = $this->driver->query($sql, $this->getConnection());
108:
109: if($this->driver->countRows($results)!=1 || $this->driver->countColumns($results)!=1)
110: {
111: throw new SQLException('Expected only 1 result with only 1 column');
112: }
113: while($row = $this->driver->resultSetArray($results))
114: {
115: $int = $row[0];
116: }
117: settype($int, Component::TYPE_INT);
118: return $int;
119: }
120: }
121:
122: ?>
123: