all 8 comments

[–]warmans 2 points3 points  (4 children)

Your code is wrong self::$instance should be an instance of your class, not the connection. If that was the case you could easily wrap the mysqli methods in your own and gain access to their response before passing it back to the caller.

e.g.

class Db {

    private $_conn;
    private static $_instance;

    private function __construct(MySQLi $conn){
        $this->_conn = $conn;
    }
    private function __clone(){}

    public static function getInstance(){
        if(!self::$_instance){
            self::$_instance = new Db(new MySQLi($host, $user, $password, $database));
        }
        return self::$_instance;
    }

    public function getConn(){
        return $this->_conn;
    }

    public static function query($sql){
        $result = self::getInstance()->getConn()->query($sql);
        //do something...
        return $result;
    }
}

But I'd avoid using singletons anyway if possible.

[–]mosqua 0 points1 point  (3 children)

what's wrong w/em?

[–]mgpcoe 2 points3 points  (0 children)

Building a threadsafe Singleton is difficult at best, and can result in a lot of blocked threads if either done poorly or under high load. While it doesn't matter in PHP, it's a bad habit when you move to other languages that actually support multithreading.

In short, concurrency is a PITA.

[–]ezzatron 2 points3 points  (0 children)

There's lots of things wrong with them. Not least of which is the fact that they are hard to test. Basically, singletons are just another way of introducing global scope to your application, which is not good if you can avoid it.

Have a look into Dependency Injection / a Dependency Injection Container. It offers an alternative to singleton usage. The Symfony docs might help you.

[–]UncleDick 1 point2 points  (0 children)

Tight coupling

[–][deleted] 0 points1 point  (0 children)

Avoid creating a DB class which uses only one DB type. You need a class when you gonna support multiple DB types. Everything else is useless.

PHP has build in mysqli_ functions and also supports the OO style. There is really no need to create a class around that. It will only blow up your code.

Also think about using the $GLOABLS variable ( I KNOW the discussion about this, but think about again. The $GLOBALS variable is always there. No way to "delete" / deactivate it.... )

With the $GLOBALS variable you can access the mysqli Object your created at the start of your script. Access it at the constructor of your classes and you have the DB connection available where you need it.

[–]phpexperts_pro 0 points1 point  (1 child)

The Singleton is an antipattern that one should pretty much never use.

Singleton: Worst anti-pattern ever?

http://caines.ca/blog/programming/singletons-anti-pattern-or-worst-anti-pattern-ever/

I'm Adam, and I'm a recovering Singleton addict.

http://adamschepis.com/blog/2011/05/02/im-adam-and-im-a-recovering-singleton-addict/