In the context of OOP in PHP, how can the Decorator Pattern be applied to enhance the functionality of a PDO connection class?
The Decorator Pattern can be applied to enhance the functionality of a PDO connection class by allowing additional features to be added dynamically to the base class without modifying its structure. This can be useful for adding functionalities like logging, caching, or encryption to the PDO connection class without altering its core implementation.
// Interface for the PDO connection class
interface DatabaseConnectionInterface {
public function query($sql);
}
// Base PDO connection class
class PDOConnection implements DatabaseConnectionInterface {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function query($sql) {
return $this->pdo->query($sql);
}
}
// Decorator class for adding logging functionality
class LoggingDecorator implements DatabaseConnectionInterface {
private $connection;
public function __construct(DatabaseConnectionInterface $connection) {
$this->connection = $connection;
}
public function query($sql) {
echo "Logging query: $sql\n";
return $this->connection->query($sql);
}
}
// Example usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$pdoConnection = new PDOConnection($pdo);
$decoratedConnection = new LoggingDecorator($pdoConnection);
$decoratedConnection->query('SELECT * FROM users');
Keywords
Related Questions
- How can conditional statements and loops be effectively used in PHP to manage and update database entries in different tables?
- How can PHP scripts be optimized to efficiently handle and process a large number of WebCam snapshots?
- What potential pitfalls should be considered when inserting and updating data in different tables in PHP?