PHP Design Patterns
Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can customize to solve a particular design problem in your code.
1. Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for database connections or configuration settings.
class Singleton {
// Hold the class instance.
private static $instance = null;
// The constructor is private to prevent creating a new instance via 'new'.
private function __construct() {
// Expensive initialization code goes here
}
// The object is created from within the class itself only if the class has no instance.
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
$obj1 = Singleton::getInstance();
$obj2 = Singleton::getInstance();
// $obj1 and $obj2 are the same object.
2. Factory Pattern
The Factory pattern is used to create objects without specifying the exact class of object that will be created. It delegates the instantiation logic to a specific method.
class Automobile {
private $make;
private $model;
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
}
class AutomobileFactory {
public static function create($make, $model) {
return new Automobile($make, $model);
}
}
// Create object using the factory
$car = AutomobileFactory::create('Bugatti', 'Chiron');