How can lazy-loading be implemented in PHP to optimize database connection usage?
Lazy-loading in PHP can be implemented by only establishing a database connection when it is actually needed, rather than connecting to the database every time the script runs. This can optimize database connection usage by minimizing the number of connections opened and closed. One way to achieve lazy-loading is by using a design pattern like the Singleton pattern to ensure that only one instance of the database connection is created and reused throughout the script execution.
class DatabaseConnection {
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 self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// Example of lazy-loading database connection
$db = DatabaseConnection::getInstance();
$connection = $db->getConnection();
// Use $connection to execute queries