Home arrow PHP arrow Page 2 - Building a Singleton Database with Restrictive Constructors in PHP 5

Building a MySQL abstraction class - PHP

In this third installment of a four-part series, I show you that a private constructor can be truly helpful when strictly implementing the Singleton design pattern. In this case, the pattern will be applied within a class that behaves like a simple MySQL abstraction layer, but the same concept can be extended to other classes.

TABLE OF CONTENTS:
  1. Building a Singleton Database with Restrictive Constructors in PHP 5
  2. Building a MySQL abstraction class
  3. Adding methods: fetching rows, finding insertion IDs and more
  4. Putting the MySQL driver to work
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
March 16, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

As I expressed in the introduction, my goal in this tutorial will consist of demonstrating how to use a private constructor within a class that will abstract the access to MySQL. In simple terms, this sample class will implement a Singleton static method, which as you may guess, will permit it to spawn only one instance of the MySQL driver.

Undoubtedly, a database abstraction class is really a good candidate for turning into a Singleton. Having said that, take a look at the following code fragment, which shows the partial definition of the class in question. Here it is:     

class MySQL

{

    private $_result = NULL;

    private $_link = NULL;

    private $_config = array();

    private static $_instance = NULL;

 

 

 

    // return Singleton instance of MySQL class

    public static function getInstance(array $config = array())

    {

        if (self::$_instance === NULL)

        {

            self::$_instance = new self($config);

        }

        return self::$_instance;

    }

   

    // private constructor

    private function __construct(array $config)

    {

        if (count($config) < 4)

        {

            throw new Exception('Invalid number of connection parameters');  

        }

        $this->_config = $config;

    }

   

    // prevent cloning class instance

    private function __clone(){}

}

As seen above, the “MySQL” abstraction class implements for the moment only two methods. The first one is the static “getInstance(),” which is responsible for returning to client code a Singleton instance of the class. On the other hand, the second one is the constructor that accepts an array of parameters required for connecting to the server and selecting a specified database.

So far, the constructor has nothing particularly special, except for a tiny subtlety: it's been declared private. The reason for doing so is self-explanatory: by preventing the constructor from being called from the outside, the unique access point to a single instance of the class is the aforementioned “getInstance()” method. That was simple to grasp, right?

In addition, to give the Singleton pattern a stricter implementation, the magic “__clone()” PHP 5 method has also been defined private, a process that avoids directly cloning instances of the class.

Even though at this point the earlier MySQL driver is only composed of a few straightforward methods, it's handy for illustrating a typical case where a private constructor can be of great help concerning the application of a specific design pattern.

Nonetheless, the driver in its current state isn’t very useful, meaning that it’s necessary to add more methods to it that extend its limited functionality. With that idea in mind, in the following section I’m going to code some additional methods. They will give the driver the ability to connect lazily to the server and run queries, fetch database rows and a few more useful tasks.

To see how these brand new methods will be defined, click on the link below and read the section to come.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: