views:

59

answers:

3

So I've found a method which looked nice to me: http://www.php.net/manual/en/class.pdo.php#97682

Requires PHP 5.3 but my host only supports 5.2 :(

So what method should I use for PDO, where it only connects to the database when needed? And reuses the same connection?

+1  A: 

you can use singleton with instance. Database::getInstance() which creates, caches and returns PDO object

ts
How would I do that? I'm new to singleton.
Johnny
look at mario's response, its quite straightforward. Singleton using class is quite similiar, you have just a little more typing
ts
Could you please show me an example?
Johnny
look at my post below
ts
A: 

Use a procedural singleton for readability:

 function db() {
      static $conn;
      if (!isset($conn)) {
           $conn = new PDO("sqlite:/tmp/db");
      }
      return $conn;
 }

This simplifies the use to for example:

 $rows = db()->query("SELECT * FROM all")->fetchAll();
mario
Interesting, does making $conn static allow it to be used for all calls of db()?
Johnny
The static is just there so the function doesn't "forget" the set variable. So the $conn is instantiated really just once, and remains active for all consecutive calls of db().
mario
A: 
class db{

   protected static $conn;
   public static function getInstance() {

      if (!isset(self::$conn)) {
           self::$conn = new PDO("sqlite:/tmp/db");
      }

      return self::$conn;
   }
 }

$rows = db::getInstance()->query("SELECT * FROM all")->fetchAll();
ts
Thanks, I guess procedural looks nicer.
Johnny