Guzzle 7 represents a significant evolution of the popular PHP HTTP client library, introducing modern PHP features and improved standards compliance. This guide outlines the key differences between Guzzle 6 and 7 to help you understand the upgrade path.
Major Changes Overview
1. PHP Version Requirements
- Guzzle 6: PHP >= 5.5 (works with 5.4 with limitations)
- Guzzle 7: PHP >= 7.2.5 (leverages modern PHP features)
This change allows Guzzle 7 to utilize PHP 7's performance improvements and modern language features.
2. Type Declarations and Return Types
Guzzle 7 embraces PHP 7's type system for better code reliability:
Guzzle 6 (no type hints):
public function request($method, $uri, array $options = [])
{
return $this->requestAsync($method, $uri, $options)->wait();
}
Guzzle 7 (with type hints):
public function request(string $method, $uri, array $options = []): ResponseInterface
{
return $this->requestAsync($method, $uri, $options)->wait();
}
3. Enhanced Exception Handling
Guzzle 7 introduces more specific exception classes for better error handling:
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
try {
$response = $client->get('https://api.example.com/users');
} catch (ClientException $e) {
// Handle 4xx client errors (400-499)
echo "Client error: " . $e->getResponse()->getStatusCode();
} catch (ServerException $e) {
// Handle 5xx server errors (500-599)
echo "Server error: " . $e->getResponse()->getStatusCode();
}
4. PSR-18 HTTP Client Compliance
Guzzle 7 fully implements PSR-18, making it interchangeable with other PSR-18 compliant HTTP clients:
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
class ApiClient
{
private ClientInterface $httpClient;
private RequestFactoryInterface $requestFactory;
public function __construct(ClientInterface $client, RequestFactoryInterface $factory)
{
$this->httpClient = $client;
$this->requestFactory = $factory;
}
}
5. Improved Promises/A+ Compliance
Guzzle 7 provides better promise handling with full Promises/A+ specification compliance:
// Async requests with improved promise handling
$promises = [
'users' => $client->getAsync('https://api.example.com/users'),
'posts' => $client->getAsync('https://api.example.com/posts'),
];
$responses = \GuzzleHttp\Promise\settle($promises)->wait();
foreach ($responses as $key => $response) {
if ($response['state'] === 'fulfilled') {
echo "{$key}: " . $response['value']->getStatusCode() . "\n";
}
}
6. Enhanced cURL Multi-Handling
Guzzle 7 uses more efficient cURL functions for concurrent requests:
- Guzzle 6: Uses
curl_multi_exec()
only - Guzzle 7: Supports
curl_multi_poll()
andcurl_multi_wait()
for better performance
This results in improved performance for concurrent HTTP requests.
7. Improved Base URI Handling
Guzzle 7 provides better URI resolution when combining base URIs with relative paths:
$client = new Client(['base_uri' => 'https://api.example.com/v1/']);
// Both versions work, but Guzzle 7 handles edge cases better
$response = $client->get('users/123'); // Resolves to: https://api.example.com/v1/users/123
$response = $client->get('/users/123'); // Resolves to: https://api.example.com/users/123
8. Enhanced Debugging Capabilities
Guzzle 7 offers improved debugging with better request/response logging:
use GuzzleHttp\Middleware;
$stack = HandlerStack::create();
$stack->push(Middleware::log(
$logger,
new MessageFormatter('{method} {uri} HTTP/{version} {req_body}')
));
$client = new Client(['handler' => $stack]);
9. Improved Streaming Support
Enhanced streaming capabilities with more customization options:
$client = new Client();
$response = $client->get('https://example.com/large-file.zip', [
'stream' => true,
'sink' => fopen('/path/to/local/file.zip', 'w')
]);
Migration Considerations
Breaking Changes
When upgrading from Guzzle 6 to 7, be aware of these breaking changes:
- PHP Version: Ensure your environment runs PHP >= 7.2.5
- Method Signatures: Some method signatures have changed due to type hints
- Exception Handling: Update catch blocks to handle specific exception types
- Middleware: Some middleware interfaces may have changed
Migration Steps
- Update Composer: Change your
composer.json
requirement:
{
"require": {
"guzzlehttp/guzzle": "^7.0"
}
}
- Run Tests: Execute your test suite to identify breaking changes
- Update Exception Handling: Utilize the new exception hierarchy
- Review Custom Middleware: Ensure compatibility with the improved middleware system
Compatibility Layer
For applications that need to support both versions temporarily:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
try {
$response = $client->request('GET', $url);
} catch (RequestException $e) {
// This works with both Guzzle 6 and 7
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
// Handle based on status code
}
}
Conclusion
Guzzle 7 represents a significant modernization of the library, bringing improved type safety, better standards compliance, and enhanced performance. While the upgrade requires PHP 7.2.5+, the benefits in terms of code reliability, performance, and maintainability make it a worthwhile investment for modern PHP applications.
Before upgrading, thoroughly test your application and review the official Guzzle upgrade guide for detailed migration instructions.