Design Patterns

Simple Factory Design Pattern

An explanation of the Simple Factory design pattern with PHP examples showing how to centralise object creation, reduce coupling, and simplify your code.

On this page
  1. Real World Example
  2. When to Use

A simple factory is an object that is used to generate an instance of an object for the client.

The simplest way of understanding a factory is as an object for creating other objects.

Real World Example

For example, suppose we have three types of car and want to create a factory that builds the car classes for us.

Start with an interface to define a car:

<?php

namespace SimpleFactory;

interface Car
{

}

Each car then implements the interface:

<?php

namespace SimpleFactory;

class Tesla implements Car
{

}

The factory itself handles the creation of each car type:

<?php

namespace SimpleFactory;

class CarFactory
{
    public function makeTesla() : Car
    {
        return new Tesla;
    }

    public function makeBmw() : Car
    {
        return new Bmw;
    }

    public function makeMercedes() : Car
    {
        return new Mercedes;
    }
}

When to Use

The simple factory is useful when you need a centralised location for creating objects. If those objects must be created in a specific way with particular parameters each time, the factory pattern lets you encapsulate that logic in one place rather than duplicating it throughout the application.

← Older
Singleton Design Pattern
Newer →
Builder Design Pattern

Newsletter

A weekly newsletter on React, Next.js, AI-assisted development, and engineering. No spam, unsubscribe any time.