如何创建一个具有依赖注入和接口的连接类?

问题描述:

我正在阅读这个SO问题:

I was reading this SO question:

PHP - 多个不同的数据库依赖注入类

顶部答案。我理解背后使用接口的概念,但我不知道如何使用它。这里是什么顶部的答案,对不起,如果我不应该在这里复制:

Top answer. I understand the concept behind using an Interface here, but I don't know how to use it. Here is what the top answer said, sorry if I'm not supposed to copy it here:

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);

我不明白是如何在类测试中完成它,测试。我的连接信息在哪里?我希望有人能帮助我完成这个mysql连接或可能pdo。

What I don't understand is how to complete it in the class test and what I am passing to test. Where is my connection information going? I was hoping someone would help me complete this for a mysql connection or maybe pdo.

您的连接信息将在MySQLDB类,所以你可以有这样的:

Your connection info would go in the MySQLDB class, so you could have something like this:

class MySQLDB implements IDatabase
{
    private $pdo; // Holds the PDO object for our connection

    // Or you can remove the parameters and hard code them if you want
    public function __construct( $username, $password, $database) {
        $this->pdo = new PDO( '...'); // Here is where you connect to the DB
    }

    public function query( $sql) {
        return $this->pdo->query( $sql); // Or use prepared statments
    }
}

的类:

$db = new MySQLDB( 'user', 'pass', 'db');

并将 $ db 的类期望 IDatabase

$obj = new Test( $db); // Dependency Injection, woo hoo!

您还可以查看MySQLDB类扩展PDO类,但这是您的设计选择。

You can also look into having the MySQLDB class extending the PDO class, but that is your design choice.

最后,你可能会更好地坚持使用PDO和摆脱所有这一切,因为它是一个伟大的抽象层,可以与许多不同的数据库。

Finally, you might be better off just sticking with PDO and getting rid of all this, as it is a great abstraction layer that works with many different databases.