Database connection using Singleton method
13 replies [Last post]
does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

Database connection using singleton method:

Singleton : some resources are exclusive, and normally we just need only one and one only of this kind resources and commonly shared among all ... for example:

* database connection
* log journal (some how maybe refer to db connection too or log file, etc)
* etc

so in this case we only want one and one only connection stream that shared among all ... or will have multiple connections that will kill the database ...

so the singleton method is the answer to this ...

eg code (taken from my new project bootstrap file using Zend Framework) :

        public function getMasterDb()
        {
                if (null === $this->_services['mdb']) {
                        $config = $this->masterDb->database;
                        $this->_services['mdb'] = Zend_Db::factory($config);
                }

                return $this->_services['mdb'];
        }


The bootstrap class name is Foo in this case for calling the db connector will be something like this:

$dbConnector = Foo::getInstance()->getMasterDB();

the code just make sure that only one and one only db connection opened. So along the coding in same state of web access, the connector will be the same. And this technique is called singleton.

any comments and add - ups are welcomed......

Question : looking at getMasterDB function (a public function) how should I modif or reorganize to make it in such that nobody can in- directly create a database connection, only the class it self can? So it becoe a real singleton implementation .....

tips: "private"

Note: maaf dalam english, next post insya'Allah dalam BM, pasal originally asalnya dari posting yang saya buat dalam internal forum in my org.

daku kecewa tak boleh nak pos apa2 lagi ...
amin007's picture
User offline. Last seen 4 weeks 3 days ago. Offline
Pro
Joined: 08/16/2009
Points: 2050

waa, well thank you for the tip but why use mdb???

p/s Laughing out loud saja tulis dalam english

does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

bang mdb tuh refer to my variable name (master db) takda kaitan dengan pear mdb ... read the coding carefully ..... Smile

maaf kerana nama var tuh mengconfused kan anda........

does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

Jawapan pada persoalan di atas :

dalam Foo Class :

private function __connectorDB() 
{
        $config = $this->masterDb->database;
        $this->_services['mdb'] = Zend_Db::factory($config); 
}

public function getMasterDb()
{
        if (null === $this->_services['mdb']) 
        {
                  $this->_services['mdb'] = $this->__connectorDB();
        }

       return $this->_services['mdb'];
}

- Allahualam ...
ps: going to KL this evening ......

does not have a status.
User offline. Last seen 4 years 50 weeks ago. Offline
Joined: 08/16/2009
Points: 0

Ni dah masuk design pattern ni. Selalunya kalau singleton ni pakai factory class. Kerja dia check kalau dah create tak keluar lagi. Kalau macam tu kena ada satu static public function, satu static private instance/variable dan satu private constructor function yang akan dipanggil oleh public static function tu.

so user akan call static public function ni dan dia check kalau private static instance tu null atau tidak, kalau null dia panggil private function utk assign value kay static instance tu kalau tak null just returns the static instance tu.

Contoh

class Singleton {
 private static $Instance;

 public function createConn() {
  if (!isset(self::$Instance))
    self::$Instance = new Singleton();

  return self::$Instance;
 }

 private function __construct {
  /*
   create $dbconn kat sini.
 */
 return $dbconn;
 }
}

so kalau call function ni dia akan create satu instance aje utk banyak call oleh satu connection. So yang bawah ni akan return value yg sama. Kalau tak percaya cuba commentkan if statement dalam createConn dia akan outputkan dua object yang berbeza.

var_dump(Singleton::createConn());
var_dump(Singleton::createConn());


does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton.

Above taken from wiki singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern) .

Sebagaimana telah diterangkan oleh bro kyusof . Itu adalah untuk Class Object tuh sendiri yang akan jadi unique. Tetapi bagaimana dengan database? Sebagaimana diterangkan oleh kyusof untuk class object begitu juga untuk database connection sebagaiman sample code di db connection di atas (menggunakan if juga untuk pastikan bahawa satu dan satunya db connection yang connected) .

Having a singleton class doesnt mean having a singleton database connection. Cara macamana coding kita handle/create that connection yang menjadikan ianya "singleton Database connection" . Kerana itu title posting adalah "Database connection using singleton method".

Terima Kasih kepada kyusof yang menerangkan lebih detail lagi yang saya tak cover dalam sample saya tersebut yang mana tidak ada class definition cuma menunjukan instance dalam class tersebut.

by the way $_service array tersebut adalah private so that user hanya boleh dapatkan hanya melalui get method.

dan untuk penarangan mengenai 'mdb' yang ditanya oleh bro amin oleh saya silap mdb bukan var tetapi array index ... Smile

Allahualam.

does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

Another thing, I'm in KL (Bandar Tasik Selatan) anybody wan't to have a Factory Singleton 'Makan/Minum' tonight . (maksudnya makan ramai ramai bayar masing masing ....) hehe........ Smile

amaida amacam ... hari tuh kat KT tak sempat jumpa..... ?

does not have a status.
User offline. Last seen 5 years 3 days ago. Offline
Joined: 08/16/2009
Points: 0

off topic

erk... patutlah tersedak. boleh je nak buat perjumpaan, tapi mungkin bulan ni bulan sibuk untuk semua.. takut nanti yang datang dua tiga kerat je.. yang lain dah kena cincang.. hehehe...

does not have a status.
User offline. Last seen 4 years 50 weeks ago. Offline
Joined: 08/16/2009
Points: 0

Saya nak bertanya semula dgn mr doubtfire, sorry doubt, singleton database connection tu utk satu user session ke atau utk semua database connection?

Kalau takut connection pd db server terlalu berat/expensive/mahal try buat database pooling ke, buat persistent connection

does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

Maaf kerana lewat jawab, moving around . Saya jumpa link yang menerangkan lebih lanjut. Sila klik dibawah:

http://www.ibm.com/developerworks/library/os-php-designptrns/

walaubagaimanapun sample tidak berkaitan Zend Framework... maybe forum owner boleh create another category supaya those people yang dok mula menggunakan zend framework boleh discuss dan share info bersama in one dedicated thread.

bro kyusuf: sebenarnya ini berkenaan algorithm, setiap kali kita load satu page berapa banyak query / db connection yg kita buat. auth, log, forum cat, forum thread tables ... banyak table yang terlibat dan normally kita mempunyai file lib berbeza untuk handle setiap table tersebut. Jadi untuk memastikan semua menggunakan db connection stream yang sama, dalam OOP kita boleh pakai singleton method untuk db connection.

Regards.

does not have a status.
User offline. Last seen 4 years 50 weeks ago. Offline
Joined: 08/16/2009
Points: 0

Hi, saya juga ada sistem mcm ni pakai satu connection saje. Saya gunakan satu main fail ctnya index.php. Ni lebih kurang apa yg semua org pakai especially dalam cms mcm drupal ke, joomla ke, mambo ke.

So page lain saya include kan from main page lah... So db connection saya init ka masa memula page (kalau boleh selambat mungkin.... bebetul sebelum first db call). dan saya tutup bila last pakai (seawal mungkin). So setiap class saya saya include db connection tu sebab satu variables masa init.

kalau utk function plak saya include dia mcm global variable.

Cth mcm ni lah.

<? 
 $dbconn = new dbconn();

 //
 buat kerja kat sisni. pass $dbconn ke setiap function
 //
 Login::BolehPercaya($dbconn,$userid);


 $dbconn->close();
?>

<?
 class Login {
  function static BolehPercaya($dbconn,$userid) {
   if ($dbconn===NULL) {
    //kalau $dbconn ni NULL baru create baru, kalau tak boleh pakai lagi. Jgn membazir.
   }
  }
 }
?>

Mcm ni saya still guna satu connection utk setiap function/class call saya.

So dalam new class ke new function kita ta payah initialize dbconn yg baru gunakan dbconn yang dah di create dalam main file kita dan include dia sebagai function parameter atau gunakan dia sebagai global var.

does not have a status.
User offline. Last seen 29 weeks 5 days ago. Offline
Joined: 08/16/2009
Points: 344

voila ... u have a "singleton db conection........"

amran : boleh buka thread Zend Framework tak? Smile

http://twitter.com/phpnetmy
sameon's picture
User offline. Last seen 13 weeks 14 hours ago. Offline
Pro
Joined: 08/22/2002
Points: 168

ahh forum yang dicreate kat sini bias sikit, sebab aku pakai jer boleh wujud Smile).

Kalau nak buat Zend. Ko buat dalam Advanced PHP punya forum.