跨类的PDO对象 [英] PDO objects across classes

查看:94
本文介绍了跨类的PDO对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找关于以下内容的一些反馈:

I'm looking for some feedback on the following:

我目前有两个类,它们正在我的PHP应用程序中使用。

I currently have two classes, which are being used in my PHP application.

一个数据库连接类,目前使用 MySQL (但切换到 PDO )。

A database connection class, which is currently using MySQL (but switching to PDO).

另一个需要数据库功能的类(具有多个函数)。

Another class (with several functions) which requires database functionality.

最好的方式设计这个,我已经阅读单例(有非常混合的评论),阅读示例,对象被简单地声明为每个方法(类函数) new 以及其中连接被分配给专用变量作为每个类的 __构造函数方法的一部分的示例(然后用 $ this-> )。

I'm looking for the best way to design this, I've read up on singletons (with very mixed reviews), read examples where objects were simply declared as new for each method (class functions), and examples where the connection was assigned to a private variable as part of a __constructor method for each class (then referenced with $this->).

那么,其他人怎么做呢?

So, how does everyone else do it? I hope you will be kind enough to perhaps give an example, and also welcome opinions on what others have read please.

我有两个单独的课程,两个单独的课程文件。我想保持干净的代码,减少不必要的数据库开销,并避免任何可以考虑过时的(如全局)。

I've got 2 separate classes, in two separate files. I want to keep clean code, reduce unnecessary overhead on the DB, and avoid anything that could be considered outdated (such as globals).

推荐答案

Database 类负责连接,应连接到数据库,创建新的PDO实例,并将其保存到字段本身

class Database {
    private $pdo;
    public __construct() {
        $this->pdo = new PDO(...);
    }
}

第二类数据库类中注入:

class WorkerClass {
    private $db;
    public __construct(Database $db) {
        $this->db = $db;
    }
}

这篇关于跨类的PDO对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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