What are some best practices for managing database connections in PHP when working with multiple classes and subclasses?
When working with multiple classes and subclasses in PHP, it is essential to efficiently manage database connections to avoid resource wastage and improve performance. One best practice is to use a singleton pattern to create a single instance of the database connection that can be shared across classes. This ensures that connections are reused rather than recreated for each class instance, reducing overhead.
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 usage
$db = Database::getInstance()->getConnection();
$stmt = $db->query('SELECT * FROM users');
Keywords
Related Questions
- What are some best practices for creating a simple page navigation system using PHP?
- In what scenarios would it be more efficient to use the explode function in PHP to handle data returned by a bash script, as opposed to writing it to a file?
- What are the best practices for querying a database column with a string list in PHP?