HomePHP Building a Singleton Database with Restrictive Constructors in PHP 5
Building a Singleton Database with Restrictive Constructors in PHP 5
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.
At first sight, declaring a constructor method protected or private in PHP 5 seems to be a rather irrelevant and even boring topic. The process doesnít differ too much from specifying one of those levels of restriction for a regular class method. However, this first impression may be misleading.
Of course, Iím not saying that using a restrictive constructor is going to change forever the way that you build your own classes, but there are a number of situations where making a constructor directly inaccessible from the outside can be much more helpful than you may think. To cite a few examples, a typical implementation of a Singleton class often requires coding a private/protected constructor, and this approach can also be used when coding classes that are meant to be accessed exclusively out of the object context.
Due to the intrinsic nature of constructors, imposing a more rigid access level on them means controlling the instantiation of classes in a given context. That's pretty easy to see from the examples mentioned above.
Given the importance that restrictive constructor have in PHP 5, the subject deserves a close look from a practical and pragmatic perspective. In consonance with this requisite, in the two previous chapters of this series I demonstrated a basic use of a protected constructor within an array iterator class, to prevent its direct instantiation. Even so, this introductory example was pretty trivial, as the same level of restriction could be easily achieved by declaring the iterator abstract.
However, in this third tutorial Iím going to create a more realistic example for you. It will make use of a private constructor in a more useful way, since this approach will be utilized for developing a Singleton class which will act like a simple abstraction layer to MySQL.
Are you feeling eager to learn the details of how this sample class will be built? Then start reading right now!