You are currently viewing Singleton and Factory Design Patterns in PHP (OOP’S)

Singleton and Factory Design Patterns in PHP (OOP’S)

Introduction:

In object-oriented programming, design patterns are reusable solutions to common problems that arise during software development. Two widely used design patterns in PHP are the Singleton pattern and the Factory pattern. In this article, we’ll delve into what these patterns are, when to use them, and provide examples to illustrate their usage.

Singleton Pattern:

The Singleton pattern ensures that a class has only one instance and provides a global access point to that instance. This pattern is useful when you need to manage a shared resource, control access to a resource, or maintain global state.

When to Use Singleton:

  • Managing a shared resource such as a database connection or a logger.
  • Controlling access to a resource, such as a configuration manager.
  • Creating a global state or managing global settings.
Example:
class Singleton {
    private static $instance;

    private function __construct() {}

    public static function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

Factory Pattern:

The Factory pattern is a creational pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. This pattern is useful when you want to create objects without specifying the exact class of object that will be created.

When to Use Factory:

  • Creating objects based on runtime conditions or parameters.
  • Encapsulating object creation logic to simplify client code.
  • Supporting multiple implementations of a common interface without exposing the concrete implementations to the client code.
Example:
interface Shape {
    public function draw();
}

class Circle implements Shape {
    public function draw() {
        echo "Drawing a circle.\n";
    }
}

class Square implements Shape {
    public function draw() {
        echo "Drawing a square.\n";
    }
}

class ShapeFactory {
    public static function createShape($type) {
        switch ($type) {
            case 'circle':
                return new Circle();
            case 'square':
                return new Square();
            default:
                throw new Exception("Unsupported shape type.");
        }
    }
}

Conclusion:

In summary, the Singleton and Factory Design Patterns ensure efficient object creation and management in PHP code. By implementing the Singleton pattern, you maintain control over global resources, while the Factory pattern encapsulates object creation logic. Integrating these patterns fosters robust, adaptable PHP applications for long-term success in software development.

Leave a Reply