/log

life.log()

Singleton mySQL database connection using PHP

with 9 comments

السلام عليكم و رحمة الله و بركاته
فيما يلي مثال على الـ Singleton Design Pattern
و هو ما يعطيك الإمكانية في الحصول علي فقط نسخة واحدة من أي مورد تريد إستخدامه .. في هذة الحالة مثلا الإتصال بقاعدة البيانات و ذلك بأن تستخدم الدالة getConnection بدلا من عمل نسخة جديدة من connection كل مرة هتحاول فيها الإتصال بقاعدة البيانات..

Following is a brief example for the singleton design patterns which will enable you from having only one instance of the resource you are controlling .. in this example it’s the mySQL database connection.
Else you will have multiple instances of the same class “connection” each time you want to connect.

define('DB_NAME', "test");
define('DB_USER', "root");
define('DB_PASS', "rootpass");
define('DB_HOST', "localhost");

class Connection{
	private static $connection_;

	private function __construct(){
		$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
		mysql_select_db(DB_NAME, $con);
		Connection::$connection_ =  $con;
	}

	public static function getConnection(){
		if( !Connection::$connection_ )
			new Connection;
		return Connection::$connection_;
	}

}

$con = Connection::getConnection();
و نسألكم الدعاء بظهر الغيب بالله عليكم :)
في رعاية الله و أمنه

Written by me

June 29th, 2010 at 11:57 am

9 Responses to 'Singleton mySQL database connection using PHP'

Subscribe to comments with RSS or TrackBack to 'Singleton mySQL database connection using PHP'.

  1. does that work across multiple requests?

    Ahmed Soliman

    29 Jun 10 at 12:07 PM

  2. if that work across multiple requests, doesn’t that make of the database connection a bottle neck to the whole system?!

    Ahmed Soliman

    29 Jun 10 at 12:14 PM

  3. BTW it’s only an example showing the singleton design pattern :)

    It actually can’t work across multiple request, but for the current request it will be only one instance available ..
    Frankly I don’t think that PHP have the option of sharing instanced between requests..

    Thanks for being here :)

    me

    29 Jun 10 at 1:29 PM

  4. Ah, I get it now :)

    Ahmed Soliman

    29 Jun 10 at 1:32 PM

  5. Not really a good illustration of the singleton DP.

    PHP imo is a singleton paradigm which means keda keda most your objects and classes exist only once per request. Introducing this DP on PHP doesn’t really show exactly why DP is required.

    Mahmoud Sakr

    29 Jun 10 at 2:56 PM

  6. Really? .. you must be kidding!?
    I -lately- believe the opposite .. I practiced some of design patterns I studied with Ahmed Soliman’s design patterns course and I didn’t find any troubles so far ..

    Different types of proxy are available, specially with all the magic methods available .. and nice implementations are around the internet with SOAP, XML_RPC and REST
    Iterator is available with the iterator and traversal interfaces ..
    Note: methods in the iterator interface may note be in the standard names that are available in other language but Arrays in PHP are actually different :D ..
    And the observer interface is in the SPL I think since 5.1 .. although it can be implemented through normal OO features ..
    I think other design patterns requires basic OO features which are available in PHP ..

    Regrading multiple requests thing .. may be serializing these objects and reusing them in the next request may solve the problem ..and this kind of problems -IMPO- is related to the nature of server side scripting not to the PHP language itself ..

    Anyway it’s nice to be Javawy but it’d be more nice if you confessed that PHP has the ability to be a nice OOP language .. ;) :*

    me

    29 Jun 10 at 3:33 PM

  7. I believe you mis-interpreted kamasheto’s comment, he didn’t say that design patterns cannot be applied to PHP, he simply said that in PHP a singleton design pattern isn’t needed.

    But I can argue that this is an incorrect statement as there is nothing like “PHP is a singleton paradigm” as this is a wrong interpretation to the “stateless request-based paradigm” which happens to be completely different from what singleton is.

    In PHP you can maintain a single copy of your object only if all your code is in the same php script, in more complex scenarios where you are calling different functions/methods from different files that access I/O resources (like databases, sockets, etc.) factories and singleton can be quite useful and there is nothing in PHP that can do that automagically for you.

    despite that fact, I still like to see some referential transparency in the design (explicit context passing == functional style) and using singletons in the way described by elsayed will break this.

    Ahmed Soliman

    29 Jun 10 at 3:46 PM

  8. Yes, indeed, what I meant by a singleton paradigm was in fact a stateless paradigm. I just put it that way to shape out a metaphor : )

    I didn’t really follow the more complex scenarios, but what I had in mind was a simple implementation of the db connector:

    // DB.php

    class DB {
    public function connect() {
    mysql_connect(‘localhost’, ‘root’, ‘admin’);
    }

    // … more db methods
    }

    DB::connect(); // every time you require your DB, simply make a connection
    // PHP keeps your last connection, so you didn’t really to keep the connection stored

    As Ahmed said I didn’t mean design patterns don’t work with PHP, rather this paradigm makes it very easy to confuse when a design pattern is useful.

    Mahmoud Sakr

    29 Jun 10 at 4:07 PM

  9. Wow, Thanks for your precious comments :)

    despite that fact, I still like to see some referential transparency in the design (explicit context passing == functional style) and using singletons in the way described by elsayed will break this.

    @Ahmed Soliman regarding “referential transparency” you are right – in a general sense -it’s not pure OO but It shouldn’t cause any problems in “EXAMPLE” context .. :)
    And I think you’d do the same Imperative style only to show the usage of the design in the same code sample specially if that didn’t effect the singleton design..
    Which is -BTW- nice feature in PHP and Python and I think all scripting languages that is OO.

    @KamaJeeto “7obe” and Ahmed “Ostazi” it’s OK I Kama’s point now ..
    And thanks for the right notation about the paradigm name..

    @Kamasheto in your example you typed

    “//PHP keeps your last connection, so you didn’t really to keep the connection stored”

    I think It’s my fault and the title of the post was misleading but- just to make sure that you got the idea – It’s more related to reusable precious resources than database connection ,so you can I meant to show the singleton not the connection itself.

    و جزاكم الله خيرا

    me

    29 Jun 10 at 6:21 PM

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes