How can PHP developers ensure better code organization and maintainability when dealing with database connections in multiple classes?
To ensure better code organization and maintainability when dealing with database connections in multiple classes, PHP developers can implement a singleton pattern for the database connection. This pattern ensures that only one instance of the database connection is created and shared across all classes, reducing the overhead of creating multiple connections and improving code consistency.
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// Example of how to use the singleton pattern for the database connection
$db = Database::getInstance()->getConnection();
$stmt = $db->prepare("SELECT * FROM users");
$stmt->execute();
$results = $stmt->fetchAll();