Skip to main content
paulund

1 min read

#design-patterns #php #oop

Simple Factory Design Pattern

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.

Related notes

  • Adapter Design Pattern

    Learn the Adapter design pattern with practical PHP examples, showing how to make incompatible inter...

  • Bridge Design Pattern

    An explanation of the Bridge design pattern with PHP examples, showing how to decouple an abstractio...

  • Builder Design Pattern

    Learn the Builder design pattern with PHP examples. Covers the Director, Builder, Concrete Builder,...


Newsletter

A weekly newsletter on backend architecture, AI-assisted development, and engineering. No spam, unsubscribe any time.