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 onl开发者_C百科y 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?
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();
you can use singleton with instance. Database::getInstance() which creates, caches and returns PDO object
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();
精彩评论