views:

125

answers:

4

What is the best way to deal with the $db_conn variable once I create a mysqli object?

I've been using

$GLOBALS['_sql'] = new mysqli(...);

But this seems dirty. The alternative that I've seen is to be constantly passing the connection var to every function that calls it, but that's a huge pain.

A: 

Have you considered taking a more object-oriented approach to your app? If your PHP code is organized into classes, then you only need to pass the database connection to the instance once (e.g. in the constructor) and then can easily access it in all of that class' methods, e.g. $this->_sql.

Jordan
A: 

What about something like

class Db {

    public static function factory() {

         return new Db();
    }

    public function __construct() {

         // Set up DB connection here
    }

}

usage like

Db::factory()->query('DELETE FROM users WHERE active = 0');

of course you'll need to program a query method.

alex
+2  A: 

I use a Singleton class that I usually call DatabaseManager. By making a static public method called getDB(), I never have to worry about passing the database around, as it will be available anywhere. Here's a brief stub:

class DatabaseManager
{
    private static $instance;
    private $db_connection;

    public initDBConnection($connectionInfo) {
          //make connection
    }

    public static function getInstance()
    {
     if (self::$instance == null) {
      $className = __CLASS__;
      self::$instance = new $className();
     }
     return self::$instance;
    }

    public static function getDB() 
    {
         return self::getInstance()->db_connection;
    }

}

Once you've initialized a database connection, you can simply call DatabaseManager::getDB() to get the database connection.

The beauty of this approach is that it's easily extended to manage connections to multiple databases, as well as ensuring that you never have more than one connection open to any one database. Makes your connections very efficient.

zombat
Innnnnnnteresting.....
Ian
A: 

The way I see it, theres 3 options for passing it around.

  • A Singleton, like alex proposed.
  • Storing it in $_GLOBAL.
  • Passing it around as a parameter.

Personally, I'd go with the Singleton. Using $_GLOBAL just doesn't feel right, and passing it as a parameter is just too annoying.

Juan