如何在PHP中为数据库连接mysqli编写依赖项注入?

时间:2018-11-26 12:07:58

标签: php

我试图写一些依赖注入,但是类文件出错。如何正确编写数据库连接类并将其用作依赖项注入?请检查以下错误。如何编写一次连接并在php文件中的任何地方调用它。

Database.php

class Database
{
    private $host ="localhost";
    private $user = "root";
    private $password="xxxx";
    private $db="";
    private $mysqli;


    function __construct($host,$user,$pass,$data) {

        $this->host     = $host;
        $this->user     = $user;
        $this->pass     = $pass;
        $this->data     = $data;
        $this->mysqli   = new mysqli($this->host, $this->user, $this->pass, $this->data);
    }

    public function query($query)
    {
        return $this->mysqli->query($query);
    }
}

Dummy.php

require_once("../apitest/database.php");

class Dummy
{
    protected $db;

    function __construct(Database $db)
    {
        $this->db = $db;
    }

    function get_test_yada(){
        return $this->db->mysqli->query("SELECT test FROM test")->fetch_object()->test;
    }
}

代码:

$test = new Dummy();
echo $test->get_test_yada();

错误

  

PHP致命错误:未捕获的TypeError:参数1传递给   Dummy :: __ construct()必须是Database的实例,未给出任何实例,   在第19行的/var/www/html/apitest/index.php中调用,并在   /var/www/html/apitest/index.php:8\n堆栈跟踪:\ n#0   /var/www/html/apitest/index.php(19):Dummy-> __ construct()\ n#1 {main} \ n   在第8行的/var/www/html/apitest/index.php中抛出

3 个答案:

答案 0 :(得分:0)

此属性$data$db在哪里?

class Database
{
    private $host ="localhost";
    private $user = "root";
    private $password="xxx";
    private $db="";
    private $mysqli;


    function __construct($host,$user,$pass,$data) {

        $this->host     = $host;
        $this->user     = $user;
        $this->pass     = $pass;
        $this->db       = $data;
        $this->mysqli   = new mysqli($this->host, $this->user, $this->pass, $this->db);
    }
}

class Dummy 
{
    protected $db;

    function __construct(Database $db)
    {
       $this->db = $db;
    }
}

答案 1 :(得分:0)

在尝试实例化Dummy对象时,您没有传递数据库实例。

它应该像这样:

<?php

$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'db';

$db = new Database($host,$user,$pass,$dbname);
$test = new Dummy($db);
echo $test->get_test_yada();

答案 2 :(得分:0)

此错误意味着您需要将Dummy 对象作为参数传递给Database对象

  

传递给Dummy :: __ construct()的参数1必须是的实例   数据库

我认为您对依赖关系注入的工作方式有错误的看法,我强烈建议您在继续之前阅读一些有关它的文章。

Wikipedia Dependency Injection

Simple tutorial about Dependency Injection in tutplus

Dependency Injection (DI) Container in PHP “中”的酷文章

PHP-DI 一个php依赖注入容器包