Factory Design Pattern in PHP

design patterns


JavaScript Design Patterns PHP jQuery MySQL Databases WordPress Algorithms HTML

Tipo IT - where your web applications live

In object oriented programming, the factory 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. This can be done by creating objects by calling a factory method. This functionality is can be specified in some sort of an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes, rather than by calling a constructor.

We can use Factory pattern in cases in which the main part of our backend logic needs to manage the objects, but not create them. We can see this in the Animal class that has a constructor and a getter method, but not the create method. Every time new Animal is needed, we call the create method in a new class called AnimalFactory which essentially extends the Animal class in a way, but it also creates new Animal object, which the Animal class, that acts as a blueprint for the Animal object, can't do.

Code example

factory pattern

That way we keep blueprint (Animal class) and creation class (AnimalFactory class) separated, and we can modify functionality of creation class one time, instead everywhere in our App where we create new animal object.

back to articles...