From 4f23451432d2927a33201e6cd50cb74574e735b6 Mon Sep 17 00:00:00 2001 From: Dominique Fournier Date: Tue, 27 Jan 2015 14:37:25 +0000 Subject: [PATCH] dbLayer : don't connect multiple times to the same database/username git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@1949 bf3deb0d-5f1a-0410-827f-c0cc1f45334c --- dblayer.php | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/dblayer.php b/dblayer.php index eac696c..081f85d 100644 --- a/dblayer.php +++ b/dblayer.php @@ -85,6 +85,9 @@ class dblayer extends PDO Attention : SQLite don't supports adding Foreign keys without deleting all the table, and re-import the datas (http://www.sqlite.org/omitted.html) */ + /** Limit to one instance of the connection to the same database */ + private static $instance = null; + /** Connection to the database engine See http://fr2.php.net/manual/en/pdo.construct.php for the $dsn format @param string $dsn PDO Data Source Name @@ -98,6 +101,16 @@ class dblayer extends PDO if (! isset ($driver[0])) throw new Exception (_("No valid DSN provided"), 500); // Force specifics initialisations + $oldInst = self::getInstance($dsn, $username); + + if ($oldInst !== null) + { + $this->db = $oldInst["db"]; + $this->sep = $oldInst["sep"]; + $this->dsn = $oldInst["dsn"]; + return; + } + switch ($driver[0]) { case "sqlite": @@ -161,6 +174,20 @@ class dblayer extends PDO break; } $this->dsn = $dsn; + self::$instance["$dsn-$username"]["db"] = $this->db; + self::$instance["$dsn-$username"]["dsn"] = $this->dsn; + self::$instance["$dsn-$username"]["sep"] = $this->sep; + } + + /** Singleton function to open one connection to each database/user wanted */ + private function getInstance ($dsn, $username) + { + if (self::$instance === null || + array_key_exists ("$dsn-$username", self::$instance) === false) + { + return null; + } + return self::$instance["$dsn-$username"]; } /** Return the connected database name from DSN used to connect */