3

I am confused on how a singleton model vs a static model works for database connections. My friend created a "static" class and showed me it but it did not make any sense on how it was static. I kind of understand the singleton method of how to create a database connection, but i'm not sure it meets my goal.

The main thing I want to do is cut down on the number of connections opened to MYSQL. I have a class with a function that calls the database quiet frequently, and there is no reason for it to make a new connection each time someone requests something that requires the database. Could someone provide a small example class for doing this with the singleton or the static method (whichever is the correct approach) that connects to the database and shows a small sample query? I would greatly appreciate it.

Oh yeah, I am using PHP 5.3 :) Please feel free to ask for additional details.

MasterGberry
  • 2,800
  • 6
  • 37
  • 56

1 Answers1

5

Consider the following example which uses the singleton design pattern to access the instance of database object.(purpose of this is to reuse the same connection again and again through out the application)

class Database {

    protected static $_dbh;
    const HOST = 'localhost';
    const DATABASE = 'dbname';
    const USERNAME = 'username';
    const PASSWORD = 'password';

    //declare the constructor as private to avoid direct instantiation.   
    private function __construct() { }

    //access the database object through the getInstance method.
    public static function getInstance() {
        if(!isset($_dbh)) {
            #Connection String.
            self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
            self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        return self::$_dbh;
    }
}

now if i have to make use of the class anywhere in the application i would simple do it like this.

require_once('database.php');
$dbh = Database::getInstance();
$sth = $dbh->query('SELECT * FROM sometable');
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

the call to Database::getInstance(); uses static method. what this basically does is it restricts you from directly instantiating the object by declaring the constructor as private, and instead it checks if the object is already instanitated. if true then return already instantiated object. else create new and return newly created object. this makes sure that same database connection is reused through out the application.

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
  • Is this connection used throughout the entire application for all of the clients who are connecting to my website or is it only used persistently for the client who called for this class. – MasterGberry Apr 16 '12 at 05:50
  • depends on your application architecture and how you make use of it. if you are using one application which uses the same class again and again then yes the connection will be reused through out application. – Ibrahim Azhar Armar Apr 16 '12 at 05:54
  • So if I had `class A { $db = Database::getInstance(); $db->query("SELECT * FROM TABLE WHERE ID = 1"); }` would this be using the same database connection for all clients? – MasterGberry Apr 16 '12 at 05:57
  • hmmm, I don't really know how PDO works, i know with MYSQL you need to make a connection with mysql_connect, then select the table with mysql_select_table, and then you can use a query with mysql_query. By default I believe mysql_query uses the default mysql connection which was created earlier. So I tested this with a singleton class I found online here: https://github.com/Quixotix/PHP-MySQL-Database-Class/blob/master/mysqldatabase.php I then tried adding "echo 'test';" to the beginning of connect(), when executing the php script multiple times it continuously echoed, can you explain why? – MasterGberry Apr 16 '12 at 06:11
  • when you actually give a call to getInstance() method a first time, it opens the connection and store it in a static class variable(property) `$_dbh`. so now `$_dbh` contains our database connection. now when we give a call to `Database::getInstance()` it will check wether the connection is already stored in the variable. if it finds then it will not create new connection and simply return the variable which holds the connection. if the variable is empty then that means the connection does not exist in this case it will create new connection and return the variable. – Ibrahim Azhar Armar Apr 16 '12 at 06:26
  • Hmmm, I understand that when you call getInstance() it will check to see if a connection is already present. Then someone else calls getInstance() while my script is executing. Does this mean that they will use the same connection I am? Then let's say 5 minutes later neither of us is on the website, and someone else connects. Now that there is no "active connection" since the class is no longer in memory would a new connection be created? – MasterGberry Apr 16 '12 at 06:29
  • i would suggest instead of using third party libraries or raw sql connection. try using PDO. you are gonna love it the way it handles and mainly because of object oriented nature. here is the tutorial to get you started http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ :) – Ibrahim Azhar Armar Apr 16 '12 at 06:30
  • i have already made it clear that the class will never create two connections no matter when and how you call it. as long as you call the connection from same class. – Ibrahim Azhar Armar Apr 16 '12 at 06:35
  • I'm a bit confused on why the echo test I did then resulted in the connection being opened multiple times, and yes I will accept your answer, you have provided a lot of information. :) – MasterGberry Apr 16 '12 at 06:44
  • connect() is simply a class method taking the connection parameters. this method is responsible for opening the database connection and assigning it to `$link` class property. `$link` holds the connection not `connect()`. so the multiple call to connect method will result in multiple echo mentioned by you. – Ibrahim Azhar Armar Apr 16 '12 at 07:01
  • Oh ok. That makes sense. So now I have the following code: `$db = MySqlDatabase::getInstance(); if (!$db->link) { $db->connect($_config['hostname'],$_config['username'],$_config['password'],$_config['database']); }` and it checks to see if a link already exists. Each time i refresh the page it seems to still create a new link though. Is the link dying once the page is finished loading? – MasterGberry Apr 16 '12 at 07:12
  • Ok, after some further reading I think I got how this system works. Thanks :D – MasterGberry Apr 16 '12 at 07:54