Advertisement
Guest User

DBConnection PHP class - Working MySQL PDO connection

a guest
Aug 12th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.73 KB | None | 0 0
  1. <?php
  2. namespace Lampfire\CloutLib\DB;
  3.  
  4. /**
  5.  * Creates a PDO object based on a given configuration. Once the instance is constructed, the
  6.  * configuration is immutable, though the internal PDO reference may change state.
  7.  * @package Database
  8.  * @author David Cloutman
  9.  */
  10. class DBConnector implements PDOWrapperInterface {
  11.     /**
  12.      * Database type
  13.      * @var string
  14.      */
  15.     protected $dbType;
  16.  
  17.     /**
  18.      * Database username
  19.      * @var string
  20.      */
  21.     protected $username;
  22.  
  23.     /**
  24.      * Database password
  25.      * @var [type]
  26.      */
  27.     protected $password;
  28.  
  29.     /**
  30.      * Database name
  31.      * @var string
  32.      */
  33.     protected $dbName;
  34.  
  35.     /**
  36.      * Database domain or I.P address.
  37.      * @var string
  38.      */
  39.     protected $hostName;
  40.  
  41.     /**
  42.      * The associated PDO object.
  43.      * @var null|\PDO
  44.      */
  45.     protected $pdo = null;
  46.  
  47.     /**
  48.      * An array of allowed values for $dbType.
  49.      */
  50.     const SUPPORTED_DB_TYPES = ['pgsql', 'mysql'];
  51.  
  52.     /**
  53.      * Create a new DBConnector instance.
  54.      * @param string $dbType Database type. Either 'mysql' or 'pgsql'.
  55.      * @param string $username The database user used to authenticate into the database server.
  56.      * @param string $password The password used to authenticate into the database server.
  57.      * @param string $dbName   The name of the database.
  58.      * @param string $hostname The domain name or IP address of the database server. Defaults to 'localhost'. An empty string will create a socket connection for Postgres (type='pgsql');
  59.      * @param int $port        The port of the database server. Defaults to usual value for $dbType.
  60.      */
  61.     function __construct($dbType, $username, $password, $dbName, $hostname = 'localhost', $port = null) {
  62.         $this->dbType = $dbType;
  63.         if(!$this->isValidDBType()) {
  64.             throw new InvalidDBTypeException();
  65.         }
  66.  
  67.         $this->username = $username;
  68.         $this->password = $password;
  69.         $this->dbName = $dbName;
  70.         $this->hostName = $hostname;
  71.         if (null === $port) {
  72.             $this->port = $this->setDefaultPort();
  73.         }
  74.     }
  75.  
  76.     /**
  77.      * Returns the type of database specified when the constructor was called. Valid values are 'mysql' or 'pgsql'.
  78.      * @return string
  79.      */
  80.     public function getDBType() {
  81.         return $dbType;
  82.     }
  83.  
  84.     /**
  85.      * Returns the database username.
  86.      * @return string
  87.      */
  88.     public function getUsername() {
  89.         return $this->username;
  90.     }
  91.  
  92.     /**
  93.      * Returns the database password.
  94.      * @return string
  95.      */
  96.     public function getPassword() {
  97.         return $this->password;
  98.     }
  99.  
  100.     /**
  101.      * Returns the database name.
  102.      * @return string
  103.      */
  104.     public function getDbName() {
  105.         return $this->dbName;
  106.     }
  107.  
  108.     /**
  109.      * Returns the database's hostname of i.p. address depending on which was configured.
  110.      * @return string
  111.      */
  112.     public function getHostName() {
  113.         return $this->hostName;
  114.     }
  115.  
  116.     /**
  117.      * Returns the PDO object generated by the connector or null if one is not associated with the connector.
  118.      * @return \PDO|null
  119.      */
  120.     public function getPDO() {
  121.         return $this->pdo;
  122.     }
  123.  
  124.     /**
  125.      * This internal function will set the $port property to the most common default for the given database type.
  126.      */
  127.     protected function setDefaultPort () {
  128.         switch ($this->dbType) {
  129.             case 'mysql':
  130.                 $this->port = 3306;
  131.                 break;
  132.             case 'pgsql':
  133.                 $this->port = 5432;
  134.                 break;
  135.  
  136.             default:
  137.                 throw new InvalidDBTypeException();
  138.                 break;
  139.         }
  140.     }
  141.  
  142.     /**
  143.      * Tests to see if the database type string supplied in the constructor matches supported databases.
  144.      * Supported types: mysql, pgsql
  145.      * @return boolean True if database type is supported.
  146.      */
  147.     protected function isValidDBType() {
  148.         if (false !== array_search(self::SUPPORTED_DB_TYPES)) {
  149.             return true;
  150.         }
  151.  
  152.         return false;
  153.     }
  154.  
  155.  
  156.     /**
  157.      * Creates a PDO connection string for the specified type of database.
  158.      * @return string         A connection string.
  159.      * @throws  \Exception Throws a base exception when $dbType is unsupported.
  160.      */
  161.     protected function generateConnectionString() {
  162.         $connectionString = '';
  163.         switch ($dbType) {
  164.             case 'mysql':
  165.                 $connectionString = "mysql:host={$this->hostName};port={$this->port};dbname={$this->dbName}";
  166.             break;
  167.             case 'pgsql':
  168.                 $connectionString .= 'pgsql:';
  169.                 $connectionString .= (empty($this->hostName)) ? '' : "host={$this->hostName};"; // Skip empty hostname to establish socket connection.
  170.                 $connectionString .= "port={$this->port};dbname={$this->dbName};user={$this->username};password={$this->password}";
  171.             break;
  172.             default:
  173.                 throw new InvalidDBTypeException();
  174.         }
  175.  
  176.         return $connectionString;
  177.     }
  178.  
  179.     /**
  180.      * Create a PDO connection. Note that you must call connect() explicitly to connect to the database. connect() is NOT called by the costructor.
  181.      * @return \PDO|null|boolean Returns a PDO object connected to the specified database on success, boolean false on failure.
  182.      *
  183.      */
  184.     public function connect() {
  185.         if(null === $this->pdo) {
  186.             try {
  187.                 $this->pdo = new \PDO('mysql:host=' . $this->hostName . ';dbname=' . $this->dbName, $this->username, $this->password);
  188.                 return $this->pdo;
  189.             }
  190.             catch (\PDOException $e) {
  191.                 error_log('Error Could not connect to database. PDOException: ' . $e->getMessage());
  192.                 return false;
  193.             }
  194.         }
  195.         return $this->pdo;
  196.     }
  197.  
  198.     /**
  199.      * Closes the PDO if no other variables reference the instance. Subsequent calls to connect() will
  200.      * create an new PDO object and a new connection. External variables referencing the PDO object will
  201.      * cause the connection to persist.
  202.      * @return null
  203.      */
  204.     public function close() {
  205.         $this->pdo = null;
  206.     }
  207.  
  208.     /**
  209.      * Automatically calls close() when the object is destroyed.
  210.      */
  211.     public function __destruct(){
  212.         $this->close();
  213.     }
  214. }
  215.  
  216. /**
  217.  * Flags a class as having a PDO object as part of its composition.
  218.  * @package Database
  219.  */
  220. interface PDOWrapperInterface {
  221.     /**
  222.      * The extending contains a retrievable PDO object as part of its composition.
  223.      * @return \PDO returns the encapsulated PDO object.
  224.      */
  225.     public function getPDO();
  226. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement