DEV Community

Cover image for Design Patterns in PHP 8: Simple factory
Max Zhuk
Max Zhuk

Posted on • Edited on

Design Patterns in PHP 8: Simple factory

Hello, fellow developers!🧑🏼‍💻

Today, we're going to delve into the Simple Factory pattern. This pattern, while not officially recognized as a formal design pattern, is a commonly used idiom in object-oriented programming that provides a way to encapsulate the instantiation of specific types of objects.

The Simple Factory pattern is all about creating an object without exposing the creation logic to the client and referring to the newly created object using a common interface. It's called a "simple factory" because it's simple to understand and implement. It's essentially a single class that acts as a kind of factory for creating other objects.

The main idea behind the Simple Factory pattern is to create objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

Imagine we're building a logistics management system that needs to support multiple types of transport like Truck, Ship, and Plane. We can use the Simple Factory pattern to create the appropriate type of transport based on the logistics requirement.

interface Transport
{
    public function deliver();
}
Enter fullscreen mode Exit fullscreen mode

In this example, Transport is the common interface for all transport types.

class Truck implements Transport
{
    public function deliver()
    {
        return "Delivery by road in a box";
    }
}

class Ship implements Transport
{
    public function deliver() {
        return "Delivery by sea in a container";
    }
}

class Plane implements Transport
{
    public function deliver() {
        return "Delivery by air in a cargo";
    }
}

class TransportFactory
{
    public function createTransport($type)
    {
        return match ($type) {
            'truck' => new Truck(),
            'ship' => new Ship(),
            'plane' => new Plane(),
            default => throw new Exception("Invalid transport type"),
        };
    }
}
Enter fullscreen mode Exit fullscreen mode

Truck, Ship, and Plane are concrete classes that implement the Transport interface. TransportFactory is the simple factory that creates the appropriate transport based on the type.

Now, let's see how we can use our Simple Factory:

$factory = new TransportFactory();

$transport = $factory->createTransport('truck');
echo $transport->deliver(); // Outputs: Delivery by road in a box

$transport = $factory->createTransport('ship');
echo $transport->deliver(); // Outputs: Delivery by sea in a container

$transport = $factory->createTransport('plane');
echo $transport->deliver(); // Outputs: Delivery by air in a cargo
Enter fullscreen mode Exit fullscreen mode

As you can see, the Simple Factory pattern allows us to create different types of transport objects without knowing the concrete classes. This makes our code more flexible and easier to maintain.

To wrap up, the Simple Factory pattern is a handy tool when you need to centralize the creation of similar types of objects. It simplifies the code and makes it more readable and maintainable.


P.S. Fellow developers, if you've found value in this article and are eager to deepen your understanding of design patterns in PHP and TypeScript, I have thrilling news for you! I am in the midst of crafting a comprehensive book that delves extensively into these topics, filled with practical examples, lucid explanations, and real-world applications of these patterns.

This book is being designed to cater to both novices and seasoned developers, aiming to bolster your understanding and implementation of design patterns in PHP and TypeScript. Whether you are aiming to refresh your existing knowledge or venture into new learning territories, this book is your perfect companion.

Moreover, your subscription will play a pivotal role in supporting the completion of this book, enabling me to continue providing you with quality content that can elevate your coding prowess to unprecedented heights.

I invite you to subscribe to my blog on dev.to for regular updates. I am eager to embark on this journey with you, helping you to escalate your coding skills to the next level!


Photo by Frans van Heerden: https://www.pexels.com/photo/grayscale-photography-of-locomotive-train-beside-factory-682078/

Top comments (3)

Collapse
 
suckup_de profile image
Lars Moelleken • Edited

Thanks for this post.

PS: we should try to prevent strings because we have much better support for symbols by the IDE + static code analysis

$factory->createTransport('truck')
Enter fullscreen mode Exit fullscreen mode

vs.

$factory->createTransport(Truck::class)
Enter fullscreen mode Exit fullscreen mode

+

/*
 * @param class-string<Transport>
 */
public function createTransport($type): Transport {
...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
zhukmax profile image
Max Zhuk • Edited

Thanks, I agree that the code will be better this way

Collapse
 
goodevilgenius profile image
Dan Jones

Types on all the methods. If you're doing PHP 8, all the arguments and returns should be typed.