I spent the last few hours trying to find the answer to the "best", the most logical, etc. a way to write a php database class to connect to one db postgres and one mysql db at the same time. In addition, I would like to accept the design of Injection Dependency, but I am new to this concept.
So far I have come up with ...
class Database { public function PgSqlConnect() { $host = 'localhost'; $dbname = '---'; $user = '---'; $pass = '---'; $timeout = 5; try { $pgsql_dbh = new PDO("pgsql:host=$host; dbname=$dbname", $user, $pass); $pgsql_dbh->setAttribute( PDO::ATTR_TIMEOUT, $timeout ); $pgsql_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); return $pgsql_dbh; } catch( PDOException $e ) { echo 'Unable to connect to database: ' . $e->getMessage(); } } public function MySqlConnect() { $host = 'localhost'; $dbname = '---'; $user = '---'; $pass = '---'; $timeout = 5; try { $mysql_dbh = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass); $mysql_dbh->setAttribute( PDO::ATTR_TIMEOUT, $timeout ); $mysql_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); return $mysql_dbh; } catch( PDOException $e ) { echo 'Unable to connect to database: ' . $e->getMessage(); } } }
Obviously, duplicate code violates the DRY approach. I know and have seen many examples of multiple db connections, but most relate to the same driver and do not provide DI capabilities.
I should also add that I considered placing the connection details in the constructor of the database class, like ...
$driver = 'mysql'; ... $mysqldb = new Database($driver,$un,$pw,...); $driver = 'pgsql'; ... $pgsqldb = new Database($driver,$un,$pw,...);
but I donβt know if this is really a good idea and how well it will work with DI.
Many thanks!
source share