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 responses to “Factory Design Pattern in PHP”

  1. app to buy followers on tiktok Avatar

    Awesome blog! Is your theme custom made or did you download it from
    somewhere? A theme like yours with a few simple tweeks would really make
    my blog stand out. Please let me know where you got your theme.
    Appreciate it

    1. thesharif-user Avatar


      It’s Blocksy theme by creativethemeshq. You can download it from here: https://wordpress.org/themes/blocksy/


Leave a Reply

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