Factory design pattern with real-life example (PHP)

Hasan Sheikh
2 min readOct 25, 2022
Photo by Lalit on Unsplash

I decided to create a series on design patterns. I search on the internet about factory design patterns with real-life examples, but I can’t find a real-life example. Everyone use Book Chair Person DB in their examples.

What is a Factory pattern?

The simple answer, it’s a creational design pattern. In the factory pattern, we create objects without exposing the creation logic to the client, and the client uses the same interface to create a new type of object.

We can say more easy way if you create a package for example Price plan a client only select free or paid plan. client can’t know what is implemented behind the seen.

Now it’s implements time. we create a email price plan. Here have two types of plans one paid another free

First, we create a interface plan. Here are two methods one getRate() & getFeatures()

PlanInterface.php

Now we create a plan. I already say, we have two plans free and paid.
we create free & paid plans with implements PlanInterface

Freeplan.php
PaidPlan.php

Now it’s time to implement our factory class. we create a factory class. the client can use this class easily and create a free and paid class object

PlanFactory.php

Now the client can easily use this factory class. Clients don’t need to know how to create free & paid plans. he/she just implement a factory create method

output.php
Result

🤗 I hope everyone enjoys it.
🙋 Follow & Subscribe: https://proghasan.medium.com/subscribe

Design Pattern

  1. Factory design pattern with real-life example (PHP)
  2. Abstract Factory Design Pattern with real life example in PHP

First of all, thank you Gary Clarke create a nice video.

--

--