How can the Registry pattern be effectively implemented in PHP classes for database connections?
The Registry pattern can be effectively implemented in PHP classes for database connections by creating a central registry class that stores and manages database connection instances. This allows for easy access to the database connection throughout the application without the need to repeatedly create new instances.
class DatabaseRegistry {
private static $connections = [];
public static function setConnection(string $name, PDO $connection) {
self::$connections[$name] = $connection;
}
public static function getConnection(string $name): PDO {
if(isset(self::$connections[$name])) {
return self::$connections[$name];
} else {
throw new Exception("Connection '$name' not found in registry.");
}
}
}
// Usage example
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
DatabaseRegistry::setConnection('default', $pdo);
// Retrieve connection
$pdo = DatabaseRegistry::getConnection('default');
Related Questions
- How can developers avoid errors related to Daylight Saving Time when manipulating timestamps in PHP?
- What steps can be taken to troubleshoot and debug PHP scripts that are throwing undefined function errors?
- Are there any common pitfalls to avoid when trying to keep user selections persistent in PHP applications?