So I'm designing a reporting system at work it's my first project written OOP and I'm stuck on the design choice for the DB class.
Obviously I only want to create one instance of the DB class per-session/user and then pass it to each of the classes that need it. What I don't know it what's best practice for implementing this. Currently I have code like the following:-

class db
    private $user = 'USER';
    private $pass = 'PASS';
    private $tables = array( 'user','report', 'etc...');

    function __construct(){

class report{
function __construct ($params = array(), $db, $user)
    //Error checking/handling trimed
    //$db is the database object we created
    $this->db = $db;

    //$this->user is the user object for the logged in user
    $this->user = $user;


public function setPermission($permissionId = 1)
    //Note the $this->db is this the best practise solution?

    //Note the $this->user is this the best practise solution?        

};//end report

I've been reading about using static classes and have just come across Singletons (though these appear to be passé already?) so what's current best practice for doing this?


Singletons in PHP are quite useless, your instances are created when the script is executed, and die when the script ends, regardless of whether they are singletons or not. This is by design, PHP follows a share nothing architecture.

Just continue doing what you already do, it even has a fancy name: constructor injection. Read up on dependency injection, and if you want to make your constructor a bit more robust, consider type hinting:

class report {
    function __construct (array $params = array(), db $db, $user)


Further reading:

  • Okay, thanks! Looks like I had thought out the best solution already. For anyone coming across this question this link:- http://fabien.potencier.org/article/11/what-is-dependency-injection Explains it nice and quickly (plus uses a big which is nice) – Stephen Oct 25 '12 at 6:33
  • @Stephen Yes, that's a great blog post. Also note that Fabien is the creator of Symfony, one of the most popular php frameworks, and Pimple, a small, easy, and straightforward DI container (if you ever need one). – yannis Oct 25 '12 at 17:08
  • @Stephen I've added a few related questions on singletons, di and constructor injection. Since DI is a new concept for you, keep in mind that it's not a panacea, it can be abused as any other concept in OO design. – yannis Oct 25 '12 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.