In this section, we will take a look at the creational patterns, such as the singleton, prototype, abstract factory, and builder patterns.
The singleton is among the first design patterns most developers learn. The goal of this design pattern is to limit the number of class instantiations to only one. What this means is that using the new
keyword on a class will always return one and the same object instance. This is a powerful concept that allows us to implement all sorts of application-wide objects, such as loggers, mailers, registries, and other bits of functionality that we may want to act as singletons. However, as we will soon see, we will avoid the new
keyword altogether, and instantiate an object via the static class method.
The following example demonstrates a possible singleton pattern implementation:
<?php class Logger { private static $instance; const TYPE_ERROR = 'error'; const TYPE_WARNING = 'warning'; const TYPE_NOTICE...