DatabaseFactory.php (1586B)
1 <?php 2 3 /** 4 * Class DatabaseFactory 5 * 6 * Use it like this: 7 * $database = DatabaseFactory::getFactory()->getConnection(); 8 * 9 * That's my personal favourite when creating a database connection. 10 * It's a slightly modified version of Jon Raphaelson's excellent answer on StackOverflow: 11 * http://stackoverflow.com/questions/130878/global-or-singleton-for-database-connection 12 * 13 * Full quote from the answer: 14 * 15 * "Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than 16 * a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide 17 * that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new 18 * connection on every invocation, you can do do that. It's flexible, instead of rigid." 19 * 20 * Thanks! Big up, mate! 21 */ 22 class DatabaseFactory 23 { 24 private static $factory; 25 private $database; 26 27 public static function getFactory() 28 { 29 if (!self::$factory) { 30 self::$factory = new DatabaseFactory(); 31 } 32 return self::$factory; 33 } 34 35 public function getConnection() { 36 if (!$this->database) { 37 $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING); 38 $this->database = new PDO( 39 Config::get('DB_TYPE') . ':host=' . Config::get('DB_HOST') . ';dbname=' . 40 Config::get('DB_NAME') . ';port=' . Config::get('DB_PORT') . ';charset=' . Config::get('DB_CHARSET'), 41 Config::get('DB_USER'), Config::get('DB_PASS'), $options 42 ); 43 } 44 return $this->database; 45 } 46 }