Silverfall05
Silverfall05

Reputation: 1127

mysqli and singleton

<?
class DbConn {
    const DB_HOST = 'localhost';
    const DB_USER = 'root';
    const DB_PASS = 'pw';
    const DB_NAME = 'db';

    static private $instance = NULL;
    private $_db;

    static function getInstance()
    {
      if (self::$instance == NULL)
      {
        self::$instance = new DbConn();
        if(mysqli_connect_errno()) {
            throw new Exception("Database connection failed: ".mysqli_connect_error());
        }
      }
      return self::$instance;
    }

    private function __construct()
    {
        $this->_db = new mysqli(self::DB_HOST, self::DB_USER, self::DB_PASS, self::DB_NAME) or die('Couldnt connect');
    }

    private function __clone() {}

}

DbConn::getInstance()->query();

?>

Im just learning and know I've got to singleton pattern, I tried to make my own DBConnect class using singleton, but when I'm trying executing it, it gives an error when calling DbConn::getInstance()->query(); saying that Call to undefined method DbConn::query() What am I doing wrong?

Upvotes: 0

Views: 2553

Answers (4)

Dori
Dori

Reputation: 1055

I'm pretty new at this, so correct me if I'm wrong.

Can't you simply extend the mysqli class and change the contructor a little?

class DbConn {

becomes

class DbConn extends mysqli {


and:

$this->_db = new mysqli(
    self::DB_HOST, 
    self::DB_USER, 
    self::DB_PASS, 
    self::DB_NAME) or die('Couldnt connect');

becomes

parent::__construct(
    self::DB_HOST, 
    self::DB_USER, 
    self::DB_PASS, 
    self::DB_NAME) or die('Couldnt connect');


Now, DbConn::getInstance()->query(); should work

Upvotes: 0

Conrad Lotz
Conrad Lotz

Reputation: 8818

Try adding the following after the __construct function

public function query($sql)
{
    return $this->_db->query($sql);
}

then try

DbConn::getInstance()->query("SELECT * FROM Table"); //Replace your sql

Upvotes: 1

JvdBerg
JvdBerg

Reputation: 21856

You have to

  • extend the mysqli class to use methods from that class
  • or write a query method yourself.
  • or make the $db public and use DbConn::getInstance()->$db->query();

Why make it a Singleton? mysqli does connection pooling, and making it a singleton add extra complexity without any benefits.

Upvotes: 0

gd1
gd1

Reputation: 11403

You are calling query() on a object of class DbConn - which hasn't got any query() method.

The implementation of the singleton pattern is good in your example. But you can't call the mysqli functions on the DbConn object directly, you have to wrap them or provide a getter for the private _db property, and call query() on that object.

Upvotes: 2

Related Questions