What are the best practices for managing database connections in PHP applications using PDO?

When managing database connections in PHP applications using PDO, it is important to follow best practices to ensure secure and efficient handling of connections. One recommended approach is to create a separate class for managing database connections, which can handle connection establishment, error handling, and closing connections properly. This helps in centralizing the database connection logic and makes it easier to maintain and scale the application.

class Database {
    private $host = 'localhost';
    private $db_name = 'database';
    private $username = 'root';
    private $password = '';

    public function getConnection() {
        $pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    }
}

// Example of using the Database class to establish a connection
$database = new Database();
$pdo = $database->getConnection();

// Perform database operations using $pdo connection