How do I create a connection class with dependency

2020-02-12 20:46发布

问题:

I was reading this SO question:

PHP - multiple different databases dependency injected class

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

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.

回答1:

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
    }
}

Then you instantiate it outside of the class:

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

And pass that $db object to one of your classes expecting an IDatabase:

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

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

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.