How does using interfaces in PHP contribute to modularity and the ability to swap out objects in a system?
Using interfaces in PHP allows for defining a contract that classes must adhere to, promoting modularity by enforcing a consistent API for different objects. This makes it easier to swap out objects with different implementations that still fulfill the interface requirements, without needing to modify the existing code that relies on those objects.
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
// Implementation for logging to a file
}
}
class DatabaseLogger implements Logger {
public function log($message) {
// Implementation for logging to a database
}
}
function logMessage(Logger $logger, $message) {
$logger->log($message);
}
$fileLogger = new FileLogger();
$dbLogger = new DatabaseLogger();
logMessage($fileLogger, "Logging to a file");
logMessage($dbLogger, "Logging to a database");
Keywords
Related Questions
- Are there any best practices or guidelines for safely reading source code from external URLs in PHP, especially when allow_url_fopen is disabled?
- What are some best practices for integrating database-driven content with Smarty templates?
- What is the purpose of hiding the .php extension in a website URL?