connector.php 2.31 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
			if (file_exists($path = APP_PATH.'storage/db/'.$config->database.'.sqlite'))
37 38 39 40 41 42 43
			{
				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
		elseif ($config->driver == 'mysql' or $config->driver == 'pgsql')
		{
54 55 56 57 58 59 60 61 62 63 64
			// -----------------------------------------------------
			// Build the PDO connection DSN.
			// -----------------------------------------------------
			$dsn = $config->driver.':host='.$config->host.';dbname='.$config->database;

			if (isset($config->port))
			{
				$dsn .= ';port='.$config->port;
			}

			$connection = new \PDO($dsn, $config->username, $config->password, static::$options);
65

66 67 68
			// -----------------------------------------------------
			// Set the appropriate character set for the datbase.
			// -----------------------------------------------------
69 70 71 72 73 74 75
			if (isset($config->charset))
			{
				$connection->prepare("SET NAMES '".$config->charset."'")->execute();
			}

			return $connection;
		}
76 77

		throw new \Exception('Database driver '.$config->driver.' is not supported.');
78 79 80
	}

}