将$ mysqli设置为OOP的全局变量 [英] Set $mysqli as a global variable for OOP

查看:39
本文介绍了将$ mysqli设置为OOP的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧, 这是一个涉及到的问题,但是任何帮助或建议都将非常令人感激.

Ok, This is sort of an involved problem, but any help or advice would be incredibly appreciated.

因此,我正在使用一个站点(使用.htaccess)将所有流量重定向到load.php.对于任何sql功能,我都有一个抽象类,该类具有许多查询语句作为传递参数以定义每个查询细节的函数.

So I'm working with a site that (using .htaccess) redirects all traffic to a load.php. For any sql functionality, I have an abstract class that has a lot of query statements as functions that pass parameters to define the specifics of each query.

例如 $ table-> update("constraints")

e.g. $table->update("constraints")

我试图弄清楚如何在load.php上设置与数据库的连接,然后将连接设置为变量($mysqli),然后可以在我的抽象查询类中引用它而不必通过每个查询函数调用的参数.

I'm trying to figure out how to set the connection to the database on load.php, and then set the connection as a variable ($mysqli) that can then be referenced in my abstract query class without having to pass the parameter to every single query function call.

再次,我们将不胜感激.

Again, any help or advice would be appreciated.

这是一个函数示例:

 function clearTable (){
    $mysqli = dbConnect::connect();
    $sql = "TRUNCATE TABLE $this->tablename";
    $mysqli->query($sql);

}

如果我在构造函数中连接到数据库并设置了$this->mysqli并将$mysqli = dbConnect::connect();替换为$mysqli = $this->mysqli,则所有查询均不起作用.尽管他们在每次通话时都进行了全新的重新连接.

If I connect to the database in a construct function and set $this->mysqli and replace $mysqli = dbConnect::connect(); with $mysqli = $this->mysqli, none of the queries work. Though they work with a fresh reconnect on each call.

推荐答案

您应该为此使用依赖注入.

You should use Dependency Injection for this.

基本上,这意味着需要数据库连接的类不会创建连接,它只会接收已经实例化的实例.

Basically it means that the class that needs the database connection doesn't create the connection, it just receives the already instasiated instance.

在某些初始化文件中:

// Create the db connection
$db = new Mysqli(......);

// Pass it to the query class that needs it
$queryClass = new QueryClass($db);

然后在您的班级文件中:

Then in your class file:

class QueryClass
{
    protected $db;

    public function __construct($db)
    {
        // $this->db will now be the same Mysql instance
        $this->db = $db;
    }

    public function doSomeQuery()
    {
        $this->db->query(....);
    }
}

这样做的好处是,如果您要开始进行一些单元测试,则无需触摸QueryClass.您只需要将数据库连接传递给测试数据库即可.

A bonus for this is that you don't need to touch the QueryClass, if you ever want to start making some unit tests. You only need to pass a DB connection to a test database instead.

这篇关于将$ mysqli设置为OOP的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆