How do I create a connection class with dependency injection and interfaces?

后端 未结 1 409
梦毁少年i
梦毁少年i 2020-12-19 18:26

I was reading this SO question:

PHP - multiple different databases dependency injected class

Top answer. I understand the concept behind using an Interface

1条回答
  •  醉梦人生
    2020-12-19 18:45

    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.

    0 讨论(0)
提交回复
热议问题