What are the best practices for making database connections available globally in a PHP application?
When developing a PHP application, it is often necessary to establish a database connection that can be accessed globally across different files and functions. One common approach to achieve this is by using a singleton pattern to create a single instance of the database connection that can be reused throughout the application.
class Database {
private static $instance = null;
private $connection;
private function __construct() {
// Establish database connection
$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;
}
}
// To use the database connection globally
$database = Database::getInstance();
$connection = $database->getConnection();
Keywords
Related Questions
- What are the potential challenges of running a webshop and a CMS parallel on the same domain in PHP?
- What are the potential security risks associated with passing user information through URLs in PHP?
- What are the potential pitfalls or challenges when using SSL certificates of different quality in PHP?