What are the best practices for managing database connections in PHP to improve performance?

Managing database connections in PHP can improve performance by reducing the overhead of establishing new connections for each request. One way to achieve this is by using connection pooling, where a pool of pre-established connections is maintained and reused as needed. Another best practice is to close connections when they are no longer needed to free up resources.

// Create a class to manage database connections using connection pooling
class DatabaseManager {
    private static $connections = [];

    public static function getConnection() {
        if (empty(self::$connections)) {
            self::$connections[] = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
        }
        
        return array_shift(self::$connections);
    }

    public static function releaseConnection($connection) {
        self::$connections[] = $connection;
    }
}

// Example of using the DatabaseManager class to get a connection
$connection = DatabaseManager::getConnection();

// Use the connection for database operations

// Release the connection when done
DatabaseManager::releaseConnection($connection);