PDO objects across classes

爷,独闯天下 提交于 2020-01-14 20:38:09

问题


I'm looking for some feedback on the following:

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

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

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

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


回答1:


The Database class, which is responsible for connecting, should be the one connecting to the database, creating the new PDO instance, and saving it to a field in itself.

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

The second class, which doesn't care where the DB connection is from, it just needs it to work should be injected with the Database class:

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



回答2:


I've always created it in the __constructor and then used $this-> to get at it. This should work for your needs but I'd encourage you to play around with different styles and see what one works best.

I would NOT create a new object with new every time, unless you have a very good reason to.



来源:https://stackoverflow.com/questions/11508070/pdo-objects-across-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!