Factory Design Pattern In PHP

In this tutorial we will demonstrate The Factory Method Pattern. This is another creational pattern which aims to creating objects from another classes without revealing the actual class implementation and also achieves the “Dependency Inversion Principle”.


the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.


so to create an object instead of using the class constructor there will be a another class that will handle creating objects of those classes. This is done by creating a factory method in the creator class which will take for example the class name and returns a new instance from it.


let’s see this in action:

in this example we will create an interface that represents the geometric shapes.

In the code above we created a class called Rectangle that extends from the Shape interface. Each shape has a position so we injected the Position class through a dependancy injection in the constructor.

Imagine we want to create instance of this class we can use the classic way with new:

It will work but Imagine we have a class for each different shape like circles, triangles, squares. Creating new instance in this way forces you to remember the class name and also has disadvantages of tight coupling.


What about creating a factory class:

here we created a factory object that takes the class name and position


let’s create another shape class:


This is another example suppose we have a class for each Car so we will create a CarFactory

In the example above represents another way of dealing with the factory pattern as it creates two interfaces one represents the Car type and one represents the Car Factory and we created different concrete implementations of each interface then the client code will call the Factory class instead of the original Car class.



Share this: