connector.php 1.89 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?php namespace System\DB;

class Connector {

	/**
	 * The PDO connection options.
	 *
	 * @var array
	 */
	public static $options = array(
			\PDO::ATTR_CASE => \PDO::CASE_LOWER,
			\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
			\PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL,
			\PDO::ATTR_STRINGIFY_FETCHES => false,
	);

	/**
	 * Establish a PDO database connection.
	 *
	 * @param  object  $config
	 * @return PDO
	 */
	public static function connect($config)
	{
25 26 27
		// -----------------------------------------------------
		// Connect to SQLite.
		// -----------------------------------------------------
28 29
		if ($config->driver == 'sqlite')
		{
30 31
			// -----------------------------------------------------
			// Check the application/db directory first.
32 33 34
			//
			// If the database doesn't exist there, maybe the full
			// path was specified as the database name?
35 36 37 38 39 40 41 42 43
			// -----------------------------------------------------
			if (file_exists($path = APP_PATH.'db/'.$config->database.'.sqlite'))
			{
				return new \PDO('sqlite:'.$path, null, null, static::$options);
			}
			elseif (file_exists($config->database))
			{
				return new \PDO('sqlite:'.$config->database, null, null, static::$options);
			}
44 45 46 47
			else
			{
				throw new \Exception("SQLite database [".$config->database."] could not be found.");
			}
48
		}
49 50 51
		// -----------------------------------------------------
		// Connect to MySQL or Postgres.
		// -----------------------------------------------------
52 53 54 55 56 57 58 59 60 61 62
		elseif ($config->driver == 'mysql' or $config->driver == 'pgsql')
		{
			$connection = new \PDO($config->driver.':host='.$config->host.';dbname='.$config->database, $config->username, $config->password, static::$options);

			if (isset($config->charset))
			{
				$connection->prepare("SET NAMES '".$config->charset."'")->execute();
			}

			return $connection;
		}
63 64

		throw new \Exception('Database driver '.$config->driver.' is not supported.');
65 66 67
	}

}