简体   繁体   中英

Best practice for using a mysqli object?

I am finally getting around to converting from procedural PHP to OO PHP, and from mysql_XXX to mysqli. I have a quick question about mysqli and OOPHP. Say I create a new mysqli object, and want to use that object on different pages to access the database. Is the best practice to put the created object into a session variable

$_SESSION['dbSession'] = new mysqli('host','user','pass','database');

that I can pass around, or is there some other [real] best practice that I should follow?

This will differ on a case by case basis, however I think it's safe to say that storing your db handler in the session is not good practice (extra memory usage, no need to save it really etc.).

You should look at dependency injection, read here . This will make unit testing a lot easier. But please, don't store it in the session. Please.

I used to create a Database class as a Singleton like this. Not everyone likes this method, but its convenient for wrapping things up.

class Database
{
   private $_instance = null;

   public static function getInstance()
   {
      if( !(self::$_instance instanceof MySQLi) )
         self::createInstance();

      return self::_instance;
   }

   private static function createInstance()
   {
       // Create DB object here and store in self::$_instance
   }
}

There would obviously be passing of configuration data and what not, that's just a psudo-summary. You could use that class like:

$myDb = Database::getInstance();

This will recreate your database connection on each individual request, but will reuse the same connection if you make multiple queries in a single request.


As far as storing your MySQLi object in the SESSION, it just won't work. You are allowed to serialize objects and place them in the $_SESSION , but some objects are special and intentionally disallow it. For example, if you try to serialize a PDO object to store in the SESSION, it will throw this error:

Fatal error: Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances' in ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM