Categories
Design Patterns

Creational Design Patterns with PHP Examples

Creational Design Patterns are a group of design patterns that give you a way to control how the object of your choice is instantiated. In this blog post, you will learn about some popular creational design patterns, what they do and how you can use them in your PHP projects.

What are Creational Design Patterns?

Creational design patterns are a type of software design pattern that deals with the creation of objects and classes. These patterns are used to make the process of creating objects and classes more efficient and organized.

Singleton is a creational design pattern that is used to ensure that only one instance of a class is created. This is helpful for ensuring that resources are not wasted when multiple instances of a class are not needed.

Prototype is a creational design pattern that is used when the process of creating an object is expensive or time-consuming. This pattern allows for objects to be created by cloning existing objects instead of creating them from scratch.

Builder is a creational design pattern that is used to create complex objects. This pattern allows for different parts of an object to be created separately and then combined together to form the final object.

List of Creational Design Patterns

There are a number of creational design patterns that can be used in PHP development. Each has its own advantages and disadvantages, so it’s important to choose the right one for the task at hand.

Singleton Pattern

The Singleton Pattern ensures that only one instance of a class can exist at a time. This is useful when you need to limit the number of resources that can be used by your application.

A simple example of Singleton Pattern in PHP:

<?php

class Singleton
{
    protected static $instance;
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    private function doSomething()
    {
    }
}

Factory Pattern

The Factory Pattern is a creational design pattern that allows you to create objects without specifying the exact class of the object that will be created.

A simple example of Factory Pattern in PHP:

<?php

class Factory
{
    public static function create($type)
    {
        switch ($type) {
            case "buzz":
                return new Buzz();
            case "fizz":
                return new Fizz();
            default:
                throw new Exception("Unknown object type");
        }
    }
}

Abstract Factory Pattern

The Abstract Factory Pattern is a creational design pattern that allows you to create objects without specifying the exact class of the object that will be created.

A simple example of Abstract Factory Pattern in PHP:

<?php

abstract class AbstractFactory
{
    abstract public function createProductA();
    abstract public function createProductB();
}

Builder Pattern

The Builder Pattern is a creational design pattern that allows you to create complex objects by specifying only their type and content.

A simple example of Builder Pattern in PHP:

<?php

class Builder
{
    public function build($config)
    {
        $obj = new Engine();
        $obj->secret = $config['password'];
        $obj->is_secure = $config['secure'];
        $obj->enabled = true;
        return $obj;
    }
}

Prototype Pattern

The Prototype Pattern is a creational design pattern that allows you to create new objects by copying existing objects.

A simple example of a Prototype Pattern in PHP:

<?php

class Prototype
{
    protected $object;
    public function __construct($object)
    {
        $this->object = $object;
    }
    public function copy()
    {
        $newObject = clone $this->object;
        $newObject->reset();
        return $newObject;
    }
}

Object Pool Pattern

The Object Pool Pattern is a creational design pattern that allows you to reuse objects that are expensive to create.

A simple example of Object Pool Pattern in PHP:

<?php

class ObjectPool
{
    protected $objects;
    public function __construct()
    {
        $this->objects = [];
    }
    public function get($object_name)
    {
        if (!isset($this->objects[$object_name])) {
            $this->objects[$object_name] = new $object_name();
        }
        return $this->objects[$object_name];
    }
}

Multiton Pattern

The Multiton Pattern is a creational design pattern that allows you to create multiple instances of a class with different names.

A simple example of Multiton Pattern in PHP:

<?php

class Multiton
{
    private static $instances = [];

    // Prevent direct object creation
    private function __construct() { }

    // Prevent object cloning
    private function __clone() { }

    public static function getInstance($instanceName)
    {
        if (!isset(self::$instances[$instanceName])) {
            self::$instances[$instanceName] = new self();
        }

        return self::$instances[$instanceName];
    }

    public function showMessage()
    {
        echo "I am Multiton!";
    }
}

Lazy Loading Pattern

The Lazy Loading Pattern is a creational design pattern that allows you to delay the creation of an object until it is needed.

A simple example of Lazi Loading Pattern in PHP:

<?php

class LazyLoad
{
    private $object;

    public function __construct()
    {
        $this->object = null;
    }

    public function loadObject()
    {
        if ($this->object === null) {
            // Initiate a object that has high overhead
            $this->object= new HeavyObject();
        }

        return $this->object;
    }
}

Conclusion

We hope you enjoyed this series on creational design patterns in PHP! As you can see, there are many different ways to create objects in PHP, each with its own advantages and disadvantages. In the end, it’s up to you to decide which pattern is best for your particular situation. Thanks for reading!

Leave a Reply

Your email address will not be published.