An Intro to Factory Design Pattern in PHP

In software development, the Factory design pattern refers to an object that is responsible for creating and delivering other objects based on a couple of parameters and the developer is not concerned with how the object is created and in this tutorial, you will see how the Factory design pattern is implemented in PHP programming language.

Let's imagine we are developing an e-commerce project which delivers goods by different methods e.g. DHL, FedEx, Motorcycle, Car, etc. There is a possibility as well that in the future new methods will be added. In situations like this, we can create a so-called Factory class that handles creating objects based on the type of delivery that the end-users have chosen. For the purpose of this tutorial, in the following code block we have just created two delivery types: 

<?php
interface DeliveryTypeInterface
{
    public function deliver();
}

class Uber implements DeliveryTypeInterface
{
    public function deliver()
    {
        return "Goods Delivered by Uber";
    }
}

class Motorcycle implements DeliveryTypeInterface
{
    public function deliver()
    {
        return "Goods Delivered by Motorcycle";
    }
}

// Other classes can be added in here
// The naming convention is that the first letter of the class name must be uppercase

class DeliveryFactory
{
    public static function chooseType($type)
    {
        $className = ucfirst($type);
        if (class_exists($className)) {
            return new $className();
        } else {
            return 'Type Not Found';
        }
    }
}

$uberObj = DeliveryFactory::chooseType('uber');
echo $uberObj->deliver();
echo "\n";
$motorcyleObj = DeliveryFactory::chooseType('motorcycle');
echo $motorcyleObj->deliver();

First, we need to have an interface called DeliveryTypeInterface which instructs the delivery type classes what to have; then the Uber and Motorcycle classes implement that interface (As you can see in the comments, you can add as many delivery types as you want.) The main class that developers will deal with is called DeliveryFactory which creates the related object based on the type of delivery chosen. If we run this file, the output will be:

Goods Delivered by Uber
Goods Delivered by Motorcycle

No need to say that based on the argument of chooseType() method in DeliveryFactory class, an object will be created and the user (developer) doesn't need to deal with the implementation details of creating objects. 

Long story short, the Factory pattern defines an interface for creating different objects but at the same time, it allows subclasses to decide which class to instantiate.

by Behzad Moradi on 2019-08-11