connector.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php namespace System\DB;
  2. class Connector {
  3. /**
  4. * The PDO connection options.
  5. *
  6. * @var array
  7. */
  8. public static $options = array(
  9. \PDO::ATTR_CASE => \PDO::CASE_LOWER,
  10. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  11. \PDO::ATTR_ORACLE_NULLS => \PDO::NULL_NATURAL,
  12. \PDO::ATTR_STRINGIFY_FETCHES => false,
  13. );
  14. /**
  15. * Establish a PDO database connection.
  16. *
  17. * @param object $config
  18. * @return PDO
  19. */
  20. public static function connect($config)
  21. {
  22. // -----------------------------------------------------
  23. // Connect to SQLite.
  24. // -----------------------------------------------------
  25. if ($config->driver == 'sqlite')
  26. {
  27. // -----------------------------------------------------
  28. // Check the application/db directory first.
  29. //
  30. // If the database doesn't exist there, maybe the full
  31. // path was specified as the database name?
  32. // -----------------------------------------------------
  33. if (file_exists($path = APP_PATH.'storage/db/'.$config->database.'.sqlite'))
  34. {
  35. return new \PDO('sqlite:'.$path, null, null, static::$options);
  36. }
  37. elseif (file_exists($config->database))
  38. {
  39. return new \PDO('sqlite:'.$config->database, null, null, static::$options);
  40. }
  41. else
  42. {
  43. throw new \Exception("SQLite database [".$config->database."] could not be found.");
  44. }
  45. }
  46. // -----------------------------------------------------
  47. // Connect to MySQL or Postgres.
  48. // -----------------------------------------------------
  49. elseif ($config->driver == 'mysql' or $config->driver == 'pgsql')
  50. {
  51. // -----------------------------------------------------
  52. // Build the PDO connection DSN.
  53. // -----------------------------------------------------
  54. $dsn = $config->driver.':host='.$config->host.';dbname='.$config->database;
  55. if (isset($config->port))
  56. {
  57. $dsn .= ';port='.$config->port;
  58. }
  59. $connection = new \PDO($dsn, $config->username, $config->password, static::$options);
  60. // -----------------------------------------------------
  61. // Set the appropriate character set for the datbase.
  62. // -----------------------------------------------------
  63. if (isset($config->charset))
  64. {
  65. $connection->prepare("SET NAMES '".$config->charset."'")->execute();
  66. }
  67. return $connection;
  68. }
  69. throw new \Exception('Database driver '.$config->driver.' is not supported.');
  70. }
  71. }