Factory Design Pattern In PHP

The factory design pattern solves a common programming problem. When you have a single point of origin for many classes with the same base class, you have need of the factory design pattern. A factory is a class that instantiates one or more of a number of classes that share the same base type, choosing the type of the instantiated object type at runtime without exposing the instantiation logic. You won’t often see this pattern appearing in basic projects, but as you move into enterprise development, it is very common.

In the following example, an object of type ShapeFactory is instantiated by the application code. Then when the getShape() method is called, the ShapeFactory object instantiates a new object which based on the logic in this function chooses which child class of the Shape class will be chosen to hold the new object. This allows a little more freedom in which types we use at runtime.

Factory Design Pattern UML Diagram

Basic Factory Design Pattern UML Diagram

Factory Design Pattern Example In PHP

The factory design pattern is very simple. The simplest example I like to use to describe it using PHP is a basic game with different kinds of enemy ships. In the following example we will start with an enemy class, and a few child classes that extend it like so:

Now if we are playing a game and wanted to call any of the enemy ship types from a single point of origin, we would spawn them using a factory class that looks something like this:

The code that calls the factory looks like this:

With output looking like this:


Published:March 13, 2016


Bookmark the permalink

Post a comment or leave a trackback: Trackback URL

Leave a Reply

Please wait...


Want to be notified when a new article is published? Enter your email address and name below to be the first to know.