php 依赖注入 数据库切换,PHP - 多个不同的数据库依赖注入类

I've spent the last several hours trying to find an answer to the "best", most logical, etc way to write a php database class to simultaneously connect to one postgresql db and one mysql db. Also, I'd like to adopt a Dependency Injection design but am new to that whole concept.

So far I've come up with...

class Database {

public function PgSqlConnect() {

/* Connect to database */

$host = 'localhost';

$dbname = '---';

$user = '---';

$pass = '---';

$timeout = 5; /* seconds */

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() {

/* Connect to database */

$host = 'localhost';

$dbname = '---';

$user = '---';

$pass = '---';

$timeout = 5; /* seconds */

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 the duplicated code violates the DRY approach. I know and have seen many examples of multiple db connections, but most deal with same driver and don't provide DI capability.

I should also add that I've considered placing the connection details into the Database class constructor as...

$driver = 'mysql';

...

$mysqldb = new Database($driver,$un,$pw,...);

$driver = 'pgsql';

...

$pgsqldb = new Database($driver,$un,$pw,...);

but I don't know if that is really a good idea nor how well it would work with DI.

Many thanks!

解决方案

You should create an interface first for all the DB operations.

interface IDatabase

{

function connect();

function query();

...

}

Then have different driver classes implementing this interface

class MySQLDB implements IDatabase

{

}

class PGSQLDB implements IDatabase

{

}

This way you can easily use dependency injection.

class Test

{

private $db;

function __construct(IDatabase $db)

{

$this->db = $db;

}

}

You can call it as:

$mysqldb = new MySQLDB();

$test = new Test($mysqldb);

or

$pgsqldb = new PGSQLDB();

$test = new Test($pgsqldb);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值