Neevo Public API
  • Namespace
  • Class
  • Tree

Namespaces

  • Neevo
    • Nette
  • None
  • PHP

Classes

  • Neevo
  • NeevoBaseStmt
  • NeevoCacheFile
  • NeevoCacheMemcache
  • NeevoCacheMemory
  • NeevoCacheSession
  • NeevoConnection
  • NeevoDriverMySQL
  • NeevoDriverMySQLi
  • NeevoDriverPgSQL
  • NeevoDriverSQLite2
  • NeevoDriverSQLite3
  • NeevoLiteral
  • NeevoLoader
  • NeevoObserverMap
  • NeevoParser
  • NeevoResult
  • NeevoResultIterator
  • NeevoRow
  • NeevoStmt

Interfaces

  • INeevoCache
  • INeevoDriver
  • INeevoObservable
  • INeevoObserver

Exceptions

  • NeevoDriverException
  • NeevoException
  • NeevoImplementationException
  1 <?php
  2 /**
  3  * Neevo - Tiny database layer for PHP. (http://neevo.smasty.net)
  4  *
  5  * This source file is subject to the MIT license that is bundled
  6  * with this package in the file license.txt.
  7  *
  8  * Copyright (c) 2011 Martin Srank (http://smasty.net)
  9  *
 10  */
 11 
 12 
 13 /**
 14  * Representation of database connection.
 15  *
 16  * Common configuration: (see also driver specific configuration)
 17  * - tablePrefix => prefix for table names
 18  * - lazy (bool) => If TRUE, connection will be established only when required.
 19  * - result
 20  *   - detectTypes (bool) => Detect column types automatically
 21  *   - formatDate => Date/time format (empty for DateTime instance).
 22  * - rowClass => Name of class to use as a row class.
 23  *
 24  * @author Martin Srank
 25  * @package Neevo
 26  */
 27 class NeevoConnection implements INeevoObservable, ArrayAccess {
 28 
 29 
 30     /** @var array */
 31     private $config;
 32 
 33     /** @var bool */
 34     private $connected = false;
 35 
 36     /** @var INeevoDriver */
 37     private $driver;
 38 
 39     /** @var string */
 40     private $parser = 'NeevoParser';
 41 
 42     /** @var NeevoObserverMap */
 43     private $observers;
 44 
 45     /** @var INeevoCache */
 46     private $cache;
 47 
 48 
 49     /**
 50      * Establish a connection.
 51      * @param array|string|Traversable $config
 52      * @param INeevoCache $cache
 53      * @return void
 54      * @throws InvalidArgumentException
 55      */
 56     public function __construct($config, INeevoCache $cache = null){
 57         $this->observers = new NeevoObserverMap;
 58 
 59         $this->cache = $cache !== null ? $cache : new NeevoCacheMemory;
 60 
 61         // Parse config
 62         if(is_string($config)){
 63             parse_str($config, $config);
 64 
 65         } elseif($config instanceof Traversable){
 66             $tmp = array();
 67             foreach($config as $key => $val){
 68                 $tmp[$key] = $val instanceof Traversable ? iterator_to_array($val) : $val;
 69             }
 70             $config = $tmp;
 71 
 72         } elseif(!is_array($config)){
 73             throw new InvalidArgumentException('Configuration must be an array, string or Traversable.');
 74         }
 75 
 76         // Default values
 77         $defaults = array(
 78             'driver' => Neevo::$defaultDriver,
 79             'lazy' => false,
 80             'rowClass' => 'NeevoRow',
 81             'tablePrefix' => '',
 82             'result' => array(
 83                 'detectTypes' => false,
 84                 'formatDate' => '',
 85             ),
 86         );
 87 
 88         // Create aliases
 89         self::alias($config, 'driver', 'extension');
 90         self::alias($config, 'username', 'user');
 91         self::alias($config, 'password', 'pass');
 92         self::alias($config, 'password', 'pswd');
 93         self::alias($config, 'host', 'hostname');
 94         self::alias($config, 'host', 'server');
 95         self::alias($config, 'database', 'db');
 96         self::alias($config, 'database', 'dbname');
 97         self::alias($config, 'tablePrefix', 'table_prefix');
 98         self::alias($config, 'tablePrefix', 'prefix');
 99         self::alias($config, 'charset', 'encoding');
100         self::alias($config, 'result.detectTypes', 'detectTypes');
101         self::alias($config, 'result.formatDate', 'formatDateTime');
102 
103         $config = array_replace_recursive($defaults, $config);
104 
105         $this->setDriver($config['driver']);
106 
107         $config['lazy'] = (bool) $config['lazy'] && strtolower($config['lazy']) !== 'false';
108         $this->config = $config;
109 
110         if($config['lazy'] === false)
111             $this->connect();
112     }
113 
114 
115     /**
116      * Close database connection.
117      * @return void
118      */
119     public function __destruct(){
120         try{
121             $this->driver->closeConnection();
122         } catch(NeevoImplementationException $e){
123 
124         }
125 
126         $this->notifyObservers(INeevoObserver::DISCONNECT);
127     }
128 
129 
130     /**
131      * Open database connection.
132      * @return void
133      */
134     public function connect(){
135         if($this->connected !== false)
136             return;
137 
138         $this->driver->connect($this->config);
139         $this->connected = true;
140         $this->notifyObservers(INeevoObserver::CONNECT);
141     }
142 
143 
144     /**
145      * Get configuration.
146      * @param string $key
147      * @return mixed
148      */
149     public function getConfig($key = null){
150         if($key === null)
151             return $this->config;
152         return isset($this->config[$key]) ? $this->config[$key] : null;
153     }
154 
155 
156     /**
157      * Get defined table prefix.
158      * @return string
159      */
160     public function getPrefix(){
161         return isset($this->config['tablePrefix']) ? $this->config['tablePrefix'] : '';
162     }
163 
164 
165     /**
166      * Get the current driver instance.
167      * @return INeevoDriver
168      */
169     public function getDriver(){
170         return $this->driver;
171     }
172 
173 
174     /**
175      * Get the current parser class name.
176      * @return string
177      */
178     public function getParser(){
179         return $this->parser;
180     }
181 
182 
183     /**
184      * Get the current cache storage instance.
185      * @return INeevoCache
186      */
187     public function getCache(){
188         return $this->cache;
189     }
190 
191 
192     /**
193      * Set the cache storage.
194      * @param INeevoCache $cache
195      */
196     public function setCache(INeevoCache $cache){
197         $this->cache = $cache;
198     }
199 
200 
201     /*  ************  Implementation of INeevoObservable  ************  */
202 
203 
204     /**
205      * Attach given observer to given $event.
206      * @param INeevoObserver $observer
207      * @param int $event
208      * @return void
209      */
210     public function attachObserver(INeevoObserver $observer, $event){
211         $this->observers->attach($observer, $event);
212     }
213 
214 
215     /**
216      * Detach given observer.
217      * @param INeevoObserver $observer
218      * @return void
219      */
220     public function detachObserver(INeevoObserver $observer){
221         $this->observers->detach($observer);
222     }
223 
224 
225     /**
226      * Notify all observers attached to given event.
227      * @param int $event
228      * @return void
229      */
230     public function notifyObservers($event){
231         foreach($this->observers as $observer){
232             if($event & $this->observers->getEvent())
233                 $observer->updateStatus($this, $event);
234         }
235     }
236 
237 
238     /*  ************  Implementation of ArrayAccess  ************  */
239 
240 
241     /**
242      * Get configuration value.
243      * @param string $key
244      * @return mixed
245      */
246     public function offsetGet($key){
247         return $this->getConfig($key);
248     }
249 
250 
251     /**
252      * Check if configuration value exists.
253      * @param mixed $key
254      * @return bool
255      */
256     public function offsetExists($key){
257         return isset($this->config[$key]);
258     }
259 
260 
261     /** @internal */
262     public function offsetSet($offset, $value){}
263 
264     /** @internal */
265     public function offsetUnset($offset){}
266 
267 
268     /*  ************  Internal methods  ************  */
269 
270 
271     /**
272      * Create an alias for configuration value.
273      * @param array $config Passed by reference
274      * @param string $key
275      * @param string $alias Alias of $key
276      * @return void
277      */
278     public static function alias(&$config, $key, $alias){
279         if(!isset($config[$alias]))
280             return;
281         $tmp = & $config;
282         foreach(explode('.', $key) as $key){
283             $tmp = & $tmp[$key];
284         }
285         if(!isset($tmp))
286             $tmp = $config[$alias];
287     }
288 
289 
290     /**
291      * Set the driver and statement parser.
292      * @param string $driver
293      * @return void
294      * @throws NeevoDriverException
295      */
296     protected function setDriver($driver){
297         if(strcasecmp($driver, 'sqlite') === 0) // Backward compatibility
298             $driver = 'SQLite2';
299 
300         $class = "NeevoDriver$driver";
301 
302         if(!class_exists($class)){
303             $file = dirname(__FILE__) . '/drivers/' . strtolower($driver) . '.php';
304 
305             if(!file_exists($file))
306                 throw new NeevoDriverException("$driver driver file ($file) does not exist.");
307             if(is_readable($file))
308                 include_once $file;
309             else
310                 throw new NeevoDriverException("$driver driver file ($file) is not readable.");
311 
312         }
313         if(!$this->isDriver($class))
314             throw new NeevoDriverException("Class '$class' is not a valid Neevo driver class.");
315 
316         $this->driver = new $class;
317 
318         // Set statement parser
319         if($this->isParser($class))
320             $this->parser = $class;
321     }
322 
323 
324     /**
325      * Check wether the given class is valid Neevo driver.
326      * @param string $class
327      * @return bool
328      */
329     protected function isDriver($class){
330         try{
331             $reflection = new ReflectionClass($class);
332             return $reflection->implementsInterface('INeevoDriver');
333         } catch(ReflectionException $e){
334             return false;
335         }
336     }
337 
338 
339     /**
340      * Check wether the given class is valid Neevo statement parser.
341      * @param string $class
342      * @return bool
343      */
344     protected function isParser($class){
345         try{
346             $reflection = new ReflectionClass($class);
347             return $reflection->isSubclassOf('NeevoParser');
348         } catch(ReflectionException $e){
349             return false;
350         }
351     }
352 
353 
354 }
355 
Neevo Public API API documentation generated by ApiGen 2.8.0