/**
  * Retrieve a database connection.
  *
  * @param string $connection_string_or_connection_name A database connection string (ex. mysql://user:pass@host[:port]/dbname)
  *   Everything after the protocol:// part is specific to the connection adapter.
  *   OR
  *   A connection name that is set in ActiveRecord\Config
  *   If null it will use the default connection specified by ActiveRecord\Config->set_default_connection
  * @return Connection
  * @see parse_connection_url
  */
 public static function instance($connection_string_or_connection_name = null)
 {
     $config = Config::instance();
     if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
         self::$datetime_format = 'Y-m-d H:i:s';
     }
     if (strpos($connection_string_or_connection_name, '://') === false) {
         $connection_string = $connection_string_or_connection_name ? $config->get_connection($connection_string_or_connection_name) : $config->get_default_connection_string();
     } else {
         $connection_string = $connection_string_or_connection_name;
     }
     if (!$connection_string) {
         throw new DatabaseException("Empty connection string");
     }
     $info = static::parse_connection_url($connection_string);
     $fqclass = static::load_adapter_class($info->protocol);
     try {
         $connection = new $fqclass($info);
         $connection->protocol = $info->protocol;
         $connection->logging = $config->get_logging();
         $connection->logger = $connection->logging ? $config->get_logger() : null;
         if (isset($info->charset)) {
             $connection->set_encoding($info->charset);
         }
     } catch (PDOException $e) {
         throw new DatabaseException($e);
     }
     return $connection;
 }
Esempio n. 2
0
 public static function getInstance($connectionString, $username, $password)
 {
     if (self::$instance == null) {
         try {
             self::$instance = new \PDO($connectionString, $username, $password);
         } catch (\PDOException $e) {
             die($e->getMessage());
         } catch (\Exception $e) {
             die($e->getMessage());
         }
     }
     return self::$instance;
 }