Factory Design Pattern in PHP

The Factory design pattern is a creational pattern that provides an interface or a method for creating objects, encapsulating the object creation logic from the client code. This makes it easier to instantiate objects without having to know the exact details of how they are created.

The Factory pattern is useful when the creation of an object is a complex task, or when the creation process may change in the future. By abstracting the creation of objects behind a Factory interface, the client code can remain flexible to changes in the creation process without requiring any modification.

A simple example of factory design pattern:


class JuiceFactory{
    public function makeJuice($type){
        if( $type == 'mango' ){
           return new MangoJuice(); 
        }else if( $type == 'lemon' ){
            return new LemonJuice();
        }else if( $type == 'water mallon' ){
            return new WaterMallonJuice();
            throw new Exception('Invalid Juice Type');

$juice_factory = new JuiceFactory();

$mango_juice = $juice_factory->makeJuice('mango');
$lemon_juice = $juice_factory->makeJuice('lemon');
$water_mallon_juice = $juice_factory->makeJuice('water mallon');

Thank you

2 thoughts on “Factory Design Pattern in PHP”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top