PHP Design Patterns - Singleton, Factory, and Observer


Design patterns are proven solutions to recurring problems in software design. In PHP, several design patterns can enhance code organization and maintainability. Here, we'll explore three common design patterns: Singleton, Factory, and Observer.


Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is useful for situations where a single point of control is required, such as a configuration manager.

class Singleton {
private static $instance;
private function __construct() {
// Private constructor to prevent external instantiation
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}

Factory Pattern

The Factory pattern is used to create objects without specifying the exact class of object that will be created. It provides an interface for creating objects and allows subclasses to alter the type of objects created. Factories are commonly used for object creation, such as creating database connections or different types of products in an e-commerce system.

interface Product {
public function getName();
}
class ConcreteProduct implements Product {
public function getName() {
return 'Concrete Product';
}
}
class ProductFactory {
public static function createProduct() {
return new ConcreteProduct();
}
}

Observer Pattern

The Observer pattern defines a one-to-many dependency between objects, so when one object changes state, all its dependents are notified and updated automatically. It is often used for implementing distributed event handling systems, where one object (the subject) maintains a list of its dependents (observers) and notifies them of state changes.

interface Observer {
public function update($message);
}
class Subject {
private $observers = [];
public function addObserver(Observer $observer) {
$this->observers[] = $observer;
}
public function notify($message) {
foreach ($this->observers as $observer) {
$observer->update($message);
}
}
}
class ConcreteObserver implements Observer {
public function update($message) {
echo "Received message: $message";
}
}

Conclusion

Design patterns are essential tools for PHP developers to solve common software design problems. The Singleton, Factory, and Observer patterns, as shown here, are just a few examples of how these patterns can improve code organization, maintainability, and flexibility in your PHP applications.