How can PHP developers efficiently manage database connections in a modular framework?
PHP developers can efficiently manage database connections in a modular framework by utilizing a singleton pattern to create a single instance of the database connection object that can be reused across different modules. This approach helps in reducing the overhead of establishing multiple connections and ensures better performance and resource utilization.
class Database {
private static $instance;
private $connection;
private function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// Example of how to use the singleton pattern to get a database connection
$db = Database::getInstance();
$connection = $db->getConnection();