BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / push / vendor / guzzlehttp / guzzle / UPGRADING.md

UPGRADING.md

UPGRADING.md 52.3 KiB Download Raw

Guzzle Upgrade Guide ====================

6.0 to 7.0 ----------

In order to take advantage of the new features of PHP, Guzzle dropped the support of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return types for functions and methods have been added wherever possible.

Please make sure:

  • You are calling a function or a method with the correct type.
  • If you extend a class of Guzzle; update all signatures on methods you override.

Other Backwards Compatibility Breaking Changes

  • Class GuzzleHttp\UriTemplate is removed.
  • Class GuzzleHttp\Exception\SeekException is removed.
  • Classes GuzzleHttp\Exception\BadResponseException, GuzzleHttp\Exception\ClientException,

GuzzleHttp\Exception\ServerException can no longer be initialized with an empty Response as argument.

  • Class GuzzleHttp\Exception\ConnectException now extends GuzzleHttp\Exception\TransferException

instead of GuzzleHttp\Exception\RequestException.

  • Function GuzzleHttp\Exception\ConnectException::getResponse() is removed.
  • Function GuzzleHttp\Exception\ConnectException::hasResponse() is removed.
  • Constant GuzzleHttp\ClientInterface::VERSION is removed. Added GuzzleHttp\ClientInterface::MAJOR_VERSION instead.
  • Function GuzzleHttp\Exception\RequestException::getResponseBodySummary is removed.

Use \GuzzleHttp\Psr7\get_message_body_summary as an alternative.

  • Function GuzzleHttp\Cookie\CookieJar::getCookieValue is removed.
  • Request option exceptions is removed. Please use http_errors.
  • Request option save_to is removed. Please use sink.
  • Pool option pool_size is removed. Please use concurrency.
  • We now look for environment variables in the $_SERVER super global, due to thread safety issues with getenv. We continue to fallback to getenv in CLI environments, for maximum compatibility.
  • The get, head, put, post, patch, delete, getAsync, headAsync, putAsync, postAsync, patchAsync, and deleteAsync methods are now implemented as genuine methods on GuzzleHttp\Client, with strong typing. The original __call implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation.
  • The log middleware will log the errors with level error instead of notice
  • Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher).

Native Functions Calls

All internal native functions calls of Guzzle are now prefixed with a slash. This change makes it impossible for method overloading by other libraries or applications. Example:

// Before:
curl_version();

// After:
\curl_version();

For the full diff you can check here.

5.0 to 6.0 ----------

Guzzle now uses PSR-7 for HTTP messages. Due to the fact that these messages are immutable, this prompted a refactoring of Guzzle to use a middleware based system rather than an event system. Any HTTP message interaction (e.g., GuzzleHttp\Message\Request) need to be updated to work with the new immutable PSR-7 request and response objects. Any event listeners or subscribers need to be updated to become middleware functions that wrap handlers (or are injected into a GuzzleHttp\HandlerStack).

  • Removed GuzzleHttp\BatchResults
  • Removed GuzzleHttp\Collection
  • Removed GuzzleHttp\HasDataTrait
  • Removed GuzzleHttp\ToArrayInterface
  • The guzzlehttp/streams dependency has been removed. Stream functionality

is now present in the GuzzleHttp\Psr7 namespace provided by the guzzlehttp/psr7 package.

  • Guzzle no longer uses ReactPHP promises and now uses the

guzzlehttp/promises library. We use a custom promise library for three significant reasons: 1. React promises (at the time of writing this) are recursive. Promise chaining and promise resolution will eventually blow the stack. Guzzle promises are not recursive as they use a sort of trampolining technique. Note: there has been movement in the React project to modify promises to no longer utilize recursion. 2. Guzzle needs to have the ability to synchronously block on a promise to wait for a result. Guzzle promises allows this functionality (and does not require the use of recursion). 3. Because we need to be able to wait on a result, doing so using React promises requires wrapping react promises with RingPHP futures. This overhead is no longer needed, reducing stack sizes, reducing complexity, and improving performance.

  • GuzzleHttp\Mimetypes has been moved to a function in

GuzzleHttp\Psr7\mimetype_from_extension and GuzzleHttp\Psr7\mimetype_from_filename.

  • GuzzleHttp\Query and GuzzleHttp\QueryParser have been removed. Query

strings must now be passed into request objects as strings, or provided to the query request option when creating requests with clients. The query option uses PHP's http_build_query to convert an array to a string. If you need a different serialization technique, you will need to pass the query string in as a string. There are a couple helper functions that will make working with query strings easier: GuzzleHttp\Psr7\parse_query and GuzzleHttp\Psr7\build_query.

  • Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware

system based on PSR-7, using RingPHP and it's middleware system as well adds more complexity than the benefits it provides. All HTTP handlers that were present in RingPHP have been modified to work directly with PSR-7 messages and placed in the GuzzleHttp\Handler namespace. This significantly reduces complexity in Guzzle, removes a dependency, and improves performance. RingPHP will be maintained for Guzzle 5 support, but will no longer be a part of Guzzle 6.

  • As Guzzle now uses a middleware based systems the event system and RingPHP

integration has been removed. Note: while the event system has been removed, it is possible to add your own type of event system that is powered by the middleware system.

  • Removed the Event namespace.
  • Removed the Subscriber namespace.
  • Removed Transaction class
  • Removed RequestFsm
  • Removed RingBridge
  • GuzzleHttp\Subscriber\Cookie is now provided by

GuzzleHttp\Middleware::cookies

  • GuzzleHttp\Subscriber\HttpError is now provided by

GuzzleHttp\Middleware::httpError

  • GuzzleHttp\Subscriber\History is now provided by

GuzzleHttp\Middleware::history

  • GuzzleHttp\Subscriber\Mock is now provided by

GuzzleHttp\Handler\MockHandler

  • GuzzleHttp\Subscriber\Prepare is now provided by

GuzzleHttp\PrepareBodyMiddleware

  • GuzzleHttp\Subscriber\Redirect is now provided by

GuzzleHttp\RedirectMiddleware

  • Guzzle now uses Psr\Http\Message\UriInterface (implements in

GuzzleHttp\Psr7\Uri) for URI support. GuzzleHttp\Url is now gone.

  • Static functions in GuzzleHttp\Utils have been moved to namespaced

functions under the GuzzleHttp namespace. This requires either a Composer based autoloader or you to include functions.php.

  • GuzzleHttp\ClientInterface::getDefaultOption has been renamed to

GuzzleHttp\ClientInterface::getConfig.

  • GuzzleHttp\ClientInterface::setDefaultOption has been removed.
  • The json and xml methods of response objects has been removed. With the

migration to strictly adhering to PSR-7 as the interface for Guzzle messages, adding methods to message interfaces would actually require Guzzle messages to extend from PSR-7 messages rather then work with them directly.

Migrating to middleware

The change to PSR-7 unfortunately required significant refactoring to Guzzle due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event system from plugins. The event system relied on mutability of HTTP messages and side effects in order to work. With immutable messages, you have to change your workflow to become more about either returning a value (e.g., functional middlewares) or setting a value on an object. Guzzle v6 has chosen the functional middleware approach.

Instead of using the event system to listen for things like the before event, you now create a stack based middleware function that intercepts a request on the way in and the promise of the response on the way out. This is a much simpler and more predictable approach than the event system and works nicely with PSR-7 middleware. Due to the use of promises, the middleware system is also asynchronous.

v5:

use GuzzleHttp\Event\BeforeEvent;
$client = new GuzzleHttp\Client();
// Get the emitter and listen to the before event.
$client->getEmitter()->on('before', function (BeforeEvent $e) {
    // Guzzle v5 events relied on mutation
    $e->getRequest()->setHeader('X-Foo', 'Bar');
});

v6:

In v6, you can modify the request before it is sent using the mapRequest middleware. The idiomatic way in v6 to modify the request/response lifecycle is to setup a handler middleware stack up front and inject the handler into a client.

use GuzzleHttp\Middleware;
// Create a handler stack that has all of the default middlewares attached
$handler = GuzzleHttp\HandlerStack::create();
// Push the handler onto the handler stack
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
    // Notice that we have to return a request object
    return $request->withHeader('X-Foo', 'Bar');
}));
// Inject the handler into the client
$client = new GuzzleHttp\Client(['handler' => $handler]);

POST Requests

This version added the form_params and multipart request options. form_params is an associative array of strings or array of strings and is used to serialize an application/x-www-form-urlencoded POST request. The multipart option is now used to send a multipart/form-data POST request.

GuzzleHttp\Post\PostFile has been removed. Use the multipart option to add POST files to a multipart/form-data request.

The body option no longer accepts an array to send POST requests. Please use multipart or form_params instead.

The base_url option has been renamed to base_uri.

4.x to 5.0 ----------

Rewritten Adapter Layer

Guzzle now uses RingPHP to send HTTP requests. The adapter option in a GuzzleHttp\Client constructor is still supported, but it has now been renamed to handler. Instead of passing a GuzzleHttp\Adapter\AdapterInterface, you must now pass a PHP callable that follows the RingPHP specification.

Removed Fluent Interfaces

Fluent interfaces were removed from the following classes:

  • GuzzleHttp\Collection
  • GuzzleHttp\Url
  • GuzzleHttp\Query
  • GuzzleHttp\Post\PostBody
  • GuzzleHttp\Cookie\SetCookie

Removed functions.php

Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following functions can be used as replacements.

  • GuzzleHttp\json_decode -> GuzzleHttp\Utils::jsonDecode
  • GuzzleHttp\get_path -> GuzzleHttp\Utils::getPath
  • GuzzleHttp\Utils::setPath -> GuzzleHttp\set_path
  • GuzzleHttp\Pool::batch -> GuzzleHttp\batch. This function is, however,

deprecated in favor of using GuzzleHttp\Pool::batch().

The "procedural" global client has been removed with no replacement (e.g., GuzzleHttp\get(), GuzzleHttp\post(), etc.). Use a GuzzleHttp\Client object as a replacement.

throwImmediately has been removed

The concept of "throwImmediately" has been removed from exceptions and error events. This control mechanism was used to stop a transfer of concurrent requests from completing. This can now be handled by throwing the exception or by cancelling a pool of requests or each outstanding future request individually.

headers event has been removed

Removed the "headers" event. This event was only useful for changing the body a response once the headers of the response were known. You can implement a similar behavior in a number of ways. One example might be to use a FnStream that has access to the transaction being sent. For example, when the first byte is written, you could check if the response headers match your expectations, and if so, change the actual stream body that is being written to.

Updates to HTTP Messages

Removed the asArray parameter from GuzzleHttp\Message\MessageInterface::getHeader. If you want to get a header value as an array, then use the newly added getHeaderAsArray() method of MessageInterface. This change makes the Guzzle interfaces compatible with the PSR-7 interfaces.

3.x to 4.0 ----------

Overarching changes:

  • Now requires PHP 5.4 or greater.
  • No longer requires cURL to send requests.
  • Guzzle no longer wraps every exception it throws. Only exceptions that are

recoverable are now wrapped by Guzzle.

  • Various namespaces have been removed or renamed.
  • No longer requiring the Symfony EventDispatcher. A custom event dispatcher

based on the Symfony EventDispatcher is now utilized in GuzzleHttp\Event\EmitterInterface (resulting in significant speed and functionality improvements).

Changes per Guzzle 3.x namespace are described below.

Batch

The Guzzle\Batch namespace has been removed. This is best left to third-parties to implement on top of Guzzle's core HTTP library.

Cache

The Guzzle\Cache namespace has been removed. (Todo: No suitable replacement has been implemented yet, but hoping to utilize a PSR cache interface).

Common

  • Removed all of the wrapped exceptions. It's better to use the standard PHP

library for unrecoverable exceptions.

  • FromConfigInterface has been removed.
  • Guzzle\Common\Version has been removed. The VERSION constant can be found

at GuzzleHttp\ClientInterface::VERSION.

Collection

  • getAll has been removed. Use toArray to convert a collection to an array.
  • inject has been removed.
  • keySearch has been removed.
  • getPath no longer supports wildcard expressions. Use something better like

JMESPath for this.

  • setPath now supports appending to an existing array via the [] notation.

Events

Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses GuzzleHttp\Event\Emitter.

  • Symfony\Component\EventDispatcher\EventDispatcherInterface is replaced by

GuzzleHttp\Event\EmitterInterface.

  • Symfony\Component\EventDispatcher\EventDispatcher is replaced by

GuzzleHttp\Event\Emitter.

  • Symfony\Component\EventDispatcher\Event is replaced by

GuzzleHttp\Event\Event, and Guzzle now has an EventInterface in GuzzleHttp\Event\EventInterface.

  • AbstractHasDispatcher has moved to a trait, HasEmitterTrait, and

HasDispatcherInterface has moved to HasEmitterInterface. Retrieving the event emitter of a request, client, etc. now uses the getEmitter method rather than the getDispatcher method.

Emitter

  • Use the once() method to add a listener that automatically removes itself

the first time it is invoked.

  • Use the listeners() method to retrieve a list of event listeners rather than

the getListeners() method.

  • Use emit() instead of dispatch() to emit an event from an emitter.
  • Use attach() instead of addSubscriber() and detach() instead of

removeSubscriber().

$mock = new Mock();
// 3.x
$request->getEventDispatcher()->addSubscriber($mock);
$request->getEventDispatcher()->removeSubscriber($mock);
// 4.x
$request->getEmitter()->attach($mock);
$request->getEmitter()->detach($mock);

Use the on() method to add a listener rather than the addListener() method.

// 3.x
$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } );
// 4.x
$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } );

Http

General changes

  • The cacert.pem certificate has been moved to src/cacert.pem.
  • Added the concept of adapters that are used to transfer requests over the

wire.

  • Simplified the event system.
  • Sending requests in parallel is still possible, but batching is no longer a

concept of the HTTP layer. Instead, you must use the complete and error events to asynchronously manage parallel request transfers.

  • Guzzle\Http\Url has moved to GuzzleHttp\Url.
  • Guzzle\Http\QueryString has moved to GuzzleHttp\Query.
  • QueryAggregators have been rewritten so that they are simply callable

functions.

  • GuzzleHttp\StaticClient has been removed. Use the functions provided in

functions.php for an easy to use static client instance.

  • Exceptions in GuzzleHttp\Exception have been updated to all extend from

GuzzleHttp\Exception\TransferException.

Client

Calling methods like get(), post(), head(), etc. no longer create and return a request, but rather creates a request, sends the request, and returns the response.

// 3.0
$request = $client->get('/');
$response = $request->send();

// 4.0
$response = $client->get('/');

// or, to mirror the previous behavior
$request = $client->createRequest('GET', '/');
$response = $client->send($request);

GuzzleHttp\ClientInterface has changed.

  • The send method no longer accepts more than one request. Use sendAll to

send multiple requests in parallel.

  • setUserAgent() has been removed. Use a default request option instead. You

could, for example, do something like: $client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent()).

  • setSslVerification() has been removed. Use default request options instead,

like $client->setConfig('defaults/verify', true).

GuzzleHttp\Client has changed.

  • The constructor now accepts only an associative array. You can include a

base_url string or array to use a URI template as the base URL of a client. You can also specify a defaults key that is an associative array of default request options. You can pass an adapter to use a custom adapter, batch_adapter to use a custom adapter for sending requests in parallel, or a message_factory to change the factory used to create HTTP requests and responses.

  • The client no longer emits a client.create_request event.
  • Creating requests with a client no longer automatically utilize a URI

template. You must pass an array into a creational method (e.g., createRequest, get, put, etc.) in order to expand a URI template.

Messages

Messages no longer have references to their counterparts (i.e., a request no longer has a reference to it's response, and a response no loger has a reference to its request). This association is now managed through a GuzzleHttp\Adapter\TransactionInterface object. You can get references to these transaction objects using request events that are emitted over the lifecycle of a request.

Requests with a body

  • GuzzleHttp\Message\EntityEnclosingRequest and

GuzzleHttp\Message\EntityEnclosingRequestInterface have been removed. The separation between requests that contain a body and requests that do not contain a body has been removed, and now GuzzleHttp\Message\RequestInterface handles both use cases.

  • Any method that previously accepts a GuzzleHttp\Response object now accept a

GuzzleHttp\Message\ResponseInterface.

  • GuzzleHttp\Message\RequestFactoryInterface has been renamed to

GuzzleHttp\Message\MessageFactoryInterface. This interface is used to create both requests and responses and is implemented in GuzzleHttp\Message\MessageFactory.

  • POST field and file methods have been removed from the request object. You

must now use the methods made available to GuzzleHttp\Post\PostBodyInterface to control the format of a POST body. Requests that are created using a standard GuzzleHttp\Message\MessageFactoryInterface will automatically use a GuzzleHttp\Post\PostBody body if the body was passed as an array or if the method is POST and no body is provided.

$request = $client->createRequest('POST', '/');
$request->getBody()->setField('foo', 'bar');
$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r')));

Headers

  • GuzzleHttp\Message\Header has been removed. Header values are now simply

represented by an array of values or as a string. Header values are returned as a string by default when retrieving a header value from a message. You can pass an optional argument of true to retrieve a header value as an array of strings instead of a single concatenated string.

  • GuzzleHttp\PostFile and GuzzleHttp\PostFileInterface have been moved to

GuzzleHttp\Post. This interface has been simplified and now allows the addition of arbitrary headers.

  • Custom headers like GuzzleHttp\Message\Header\Link have been removed. Most

of the custom headers are now handled separately in specific subscribers/plugins, and GuzzleHttp\Message\HeaderValues::parseParams() has been updated to properly handle headers that contain parameters (like the Link header).

Responses

  • GuzzleHttp\Message\Response::getInfo() and

GuzzleHttp\Message\Response::setInfo() have been removed. Use the event system to retrieve this type of information.

  • GuzzleHttp\Message\Response::getRawHeaders() has been removed.
  • GuzzleHttp\Message\Response::getMessage() has been removed.
  • GuzzleHttp\Message\Response::calculateAge() and other cache specific

methods have moved to the CacheSubscriber.

  • Header specific helper functions like getContentMd5() have been removed.

Just use getHeader('Content-MD5') instead.

  • GuzzleHttp\Message\Response::setRequest() and

GuzzleHttp\Message\Response::getRequest() have been removed. Use the event system to work with request and response objects as a transaction.

  • GuzzleHttp\Message\Response::getRedirectCount() has been removed. Use the

Redirect subscriber instead.

  • GuzzleHttp\Message\Response::isSuccessful() and other related methods have

been removed. Use getStatusCode() instead.

Streaming responses

Streaming requests can now be created by a client directly, returning a GuzzleHttp\Message\ResponseInterface object that contains a body stream referencing an open PHP HTTP stream.

// 3.0
use Guzzle\Stream\PhpStreamRequestFactory;
$request = $client->get('/');
$factory = new PhpStreamRequestFactory();
$stream = $factory->fromRequest($request);
$data = $stream->read(1024);

// 4.0
$response = $client->get('/', ['stream' => true]);
// Read some data off of the stream in the response body
$data = $response->getBody()->read(1024);

Redirects

The configureRedirects() method has been removed in favor of a allow_redirects request option.

// Standard redirects with a default of a max of 5 redirects
$request = $client->createRequest('GET', '/', ['allow_redirects' => true]);

// Strict redirects with a custom number of redirects
$request = $client->createRequest('GET', '/', [
    'allow_redirects' => ['max' => 5, 'strict' => true]
]);

EntityBody

EntityBody interfaces and classes have been removed or moved to GuzzleHttp\Stream. All classes and interfaces that once required GuzzleHttp\EntityBodyInterface now require GuzzleHttp\Stream\StreamInterface. Creating a new body for a request no longer uses GuzzleHttp\EntityBody::factory but now uses GuzzleHttp\Stream\Stream::factory or even better: GuzzleHttp\Stream\create().

  • Guzzle\Http\EntityBodyInterface is now GuzzleHttp\Stream\StreamInterface
  • Guzzle\Http\EntityBody is now GuzzleHttp\Stream\Stream
  • Guzzle\Http\CachingEntityBody is now GuzzleHttp\Stream\CachingStream
  • Guzzle\Http\ReadLimitEntityBody is now GuzzleHttp\Stream\LimitStream
  • Guzzle\Http\IoEmittyinEntityBody has been removed.

Request lifecycle events

Requests previously submitted a large number of requests. The number of events emitted over the lifecycle of a request has been significantly reduced to make it easier to understand how to extend the behavior of a request. All events emitted during the lifecycle of a request now emit a custom GuzzleHttp\Event\EventInterface object that contains context providing methods and a way in which to modify the transaction at that specific point in time (e.g., intercept the request and set a response on the transaction).

  • request.before_send has been renamed to before and now emits a

GuzzleHttp\Event\BeforeEvent

  • request.complete has been renamed to complete and now emits a

GuzzleHttp\Event\CompleteEvent.

  • request.sent has been removed. Use complete.
  • request.success has been removed. Use complete.
  • error is now an event that emits a GuzzleHttp\Event\ErrorEvent.
  • request.exception has been removed. Use error.
  • request.receive.status_line has been removed.
  • curl.callback.progress has been removed. Use a custom StreamInterface to

maintain a status update.

  • curl.callback.write has been removed. Use a custom StreamInterface to

intercept writes.

  • curl.callback.read has been removed. Use a custom StreamInterface to

intercept reads.

headers is a new event that is emitted after the response headers of a request have been received before the body of the response is downloaded. This event emits a GuzzleHttp\Event\HeadersEvent.

You can intercept a request and inject a response using the intercept() event of a GuzzleHttp\Event\BeforeEvent, GuzzleHttp\Event\CompleteEvent, and GuzzleHttp\Event\ErrorEvent event.

Inflection

The Guzzle\Inflection namespace has been removed. This is not a core concern of Guzzle.

Iterator

The Guzzle\Iterator namespace has been removed.

  • Guzzle\Iterator\AppendIterator, Guzzle\Iterator\ChunkedIterator, and

Guzzle\Iterator\MethodProxyIterator are nice, but not a core requirement of Guzzle itself.

  • Guzzle\Iterator\FilterIterator is no longer needed because an equivalent

class is shipped with PHP 5.4.

  • Guzzle\Iterator\MapIterator is not really needed when using PHP 5.5 because

it's easier to just wrap an iterator in a generator that maps values.

For a replacement of these iterators, see https://github.com/nikic/iter

Log

The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The Guzzle\Log namespace has been removed. Guzzle now relies on Psr\Log\LoggerInterface for all logging. The MessageFormatter class has been moved to GuzzleHttp\Subscriber\Log\Formatter.

Parser

The Guzzle\Parser namespace has been removed. This was previously used to make it possible to plug in custom parsers for cookies, messages, URI templates, and URLs; however, this level of complexity is not needed in Guzzle so it has been removed.

  • Cookie: Cookie parsing logic has been moved to

GuzzleHttp\Cookie\SetCookie::fromString.

  • Message: Message parsing logic for both requests and responses has been moved

to GuzzleHttp\Message\MessageFactory::fromMessage. Message parsing is only used in debugging or deserializing messages, so it doesn't make sense for Guzzle as a library to add this level of complexity to parsing messages.

  • UriTemplate: URI template parsing has been moved to

GuzzleHttp\UriTemplate. The Guzzle library will automatically use the PECL URI template library if it is installed.

  • Url: URL parsing is now performed in GuzzleHttp\Url::fromString (previously

it was Guzzle\Http\Url::factory()). If custom URL parsing is necessary, then developers are free to subclass GuzzleHttp\Url.

Plugin

The Guzzle\Plugin namespace has been renamed to GuzzleHttp\Subscriber. Several plugins are shipping with the core Guzzle library under this namespace.

  • GuzzleHttp\Subscriber\Cookie: Replaces the old CookiePlugin. Cookie jar

code has moved to GuzzleHttp\Cookie.

  • GuzzleHttp\Subscriber\History: Replaces the old HistoryPlugin.
  • GuzzleHttp\Subscriber\HttpError: Throws errors when a bad HTTP response is

received.

  • GuzzleHttp\Subscriber\Mock: Replaces the old MockPlugin.
  • GuzzleHttp\Subscriber\Prepare: Prepares the body of a request just before

sending. This subscriber is attached to all requests by default.

  • GuzzleHttp\Subscriber\Redirect: Replaces the RedirectPlugin.

The following plugins have been removed (third-parties are free to re-implement these if needed):

  • GuzzleHttp\Plugin\Async has been removed.
  • GuzzleHttp\Plugin\CurlAuth has been removed.
  • GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin has been removed. This

functionality should instead be implemented with event listeners that occur after normal response parsing occurs in the guzzle/command package.

The following plugins are not part of the core Guzzle package, but are provided in separate repositories:

  • Guzzle\Http\Plugin\BackoffPlugin has been rewritten to be much simpler

to build custom retry policies using simple functions rather than various chained classes. See: https://github.com/guzzle/retry-subscriber

  • Guzzle\Http\Plugin\Cache\CachePlugin has moved to

https://github.com/guzzle/cache-subscriber

  • Guzzle\Http\Plugin\Log\LogPlugin has moved to

https://github.com/guzzle/log-subscriber

  • Guzzle\Http\Plugin\Md5\Md5Plugin has moved to

https://github.com/guzzle/message-integrity-subscriber

  • Guzzle\Http\Plugin\Mock\MockPlugin has moved to

GuzzleHttp\Subscriber\MockSubscriber.

  • Guzzle\Http\Plugin\Oauth\OauthPlugin has moved to

https://github.com/guzzle/oauth-subscriber

Service

The service description layer of Guzzle has moved into two separate packages:

  • https://github.com/guzzle/command Provides a high level abstraction over web

services by representing web service operations using commands.

  • https://github.com/guzzle/guzzle-services Provides an implementation of

guzzle/command that provides request serialization and response parsing using Guzzle service descriptions.

Stream

Stream have moved to a separate package available at https://github.com/guzzle/streams.

Guzzle\Stream\StreamInterface has been given a large update to cleanly take on the responsibilities of Guzzle\Http\EntityBody and Guzzle\Http\EntityBodyInterface now that they have been removed. The number of methods implemented by the StreamInterface has been drastically reduced to allow developers to more easily extend and decorate stream behavior.

Removed methods from StreamInterface

  • getStream and setStream have been removed to better encapsulate streams.
  • getMetadata and setMetadata have been removed in favor of

GuzzleHttp\Stream\MetadataStreamInterface.

  • getWrapper, getWrapperData, getStreamType, and getUri have all been

removed. This data is accessible when using streams that implement GuzzleHttp\Stream\MetadataStreamInterface.

  • rewind has been removed. Use seek(0) for a similar behavior.

Renamed methods

  • detachStream has been renamed to detach.
  • feof has been renamed to eof.
  • ftell has been renamed to tell.
  • readLine has moved from an instance method to a static class method of

GuzzleHttp\Stream\Stream.

Metadata streams

GuzzleHttp\Stream\MetadataStreamInterface has been added to denote streams that contain additional metadata accessible via getMetadata(). GuzzleHttp\Stream\StreamInterface::getMetadata and GuzzleHttp\Stream\StreamInterface::setMetadata have been removed.

StreamRequestFactory

The entire concept of the StreamRequestFactory has been removed. The way this was used in Guzzle 3 broke the actual interface of sending streaming requests (instead of getting back a Response, you got a StreamInterface). Streaming PHP requests are now implemented through the GuzzleHttp\Adapter\StreamAdapter.

3.6 to 3.7 ----------

Deprecations

  • You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.:
\Guzzle\Common\Version::$emitWarnings = true;

The following APIs and options have been marked as deprecated:

  • Marked Guzzle\Http\Message\Request::isResponseBodyRepeatable() as deprecated. Use $request->getResponseBody()->isRepeatable() instead.
  • Marked Guzzle\Http\Message\Request::canCache() as deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest() instead.
  • Marked Guzzle\Http\Message\Request::canCache() as deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest() instead.
  • Marked Guzzle\Http\Message\Request::setIsRedirect() as deprecated. Use the HistoryPlugin instead.
  • Marked Guzzle\Http\Message\Request::isRedirect() as deprecated. Use the HistoryPlugin instead.
  • Marked Guzzle\Cache\CacheAdapterFactory::factory() as deprecated
  • Marked Guzzle\Service\Client::enableMagicMethods() as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client.
  • Marked Guzzle\Parser\Url\UrlParser as deprecated. Just use PHP's parse_url() and percent encode your UTF-8.
  • Marked Guzzle\Common\Collection::inject() as deprecated.
  • Marked Guzzle\Plugin\CurlAuth\CurlAuthPlugin as deprecated. Use

$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any')); or $client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));

3.7 introduces request.options as a parameter for a client configuration and as an optional argument to all creational request methods. When paired with a client's configuration settings, these options allow you to specify default settings for various aspects of a request. Because these options make other previous configuration options redundant, several configuration options and methods of a client and AbstractCommand have been deprecated.

  • Marked Guzzle\Service\Client::getDefaultHeaders() as deprecated. Use $client->getDefaultOption('headers').
  • Marked Guzzle\Service\Client::setDefaultHeaders() as deprecated. Use $client->setDefaultOption('headers/{header_name}', 'value').
  • Marked 'request.params' for Guzzle\Http\Client as deprecated. Use $client->setDefaultOption('params/{param_name}', 'value')
  • Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0

$command = $client->getCommand('foo', array( 'command.headers' => array('Test' => '123'), 'command.response_body' => '/path/to/file' ));

// Should be changed to:

$command = $client->getCommand('foo', array( 'command.request_options' => array( 'headers' => array('Test' => '123'), 'save_as' => '/path/to/file' ) ));

Interface changes

Additions and changes (you will need to update any implementations or subclasses you may have created):

  • Added an $options argument to the end of the following methods of Guzzle\Http\ClientInterface:

createRequest, head, delete, put, patch, post, options, prepareRequest

  • Added an $options argument to the end of Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()
  • Added an applyOptions() method to Guzzle\Http\Message\Request\RequestFactoryInterface
  • Changed Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null) to

Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array()). You can still pass in a resource, string, or EntityBody into the $options parameter to specify the download location of the response.

  • Changed Guzzle\Common\Collection::__construct($data) to no longer accepts a null value for $data but a

default array()

  • Added Guzzle\Stream\StreamInterface::isRepeatable
  • Made Guzzle\Http\Client::expandTemplate and getUriTemplate protected methods.

The following methods were removed from interfaces. All of these methods are still available in the concrete classes that implement them, but you should update your code to use alternative methods:

  • Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use

$client->getConfig()->setPath('request.options/headers/{header_name}', 'value'). or $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value')) or $client->setDefaultOption('headers/{header_name}', 'value'). or $client->setDefaultOption('headers', array('header_name' => 'value')).

  • Removed Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`.
  • Removed Guzzle\Http\ClientInterface::expandTemplate(). This is an implementation detail.
  • Removed Guzzle\Http\ClientInterface::setRequestFactory(). This is an implementation detail.
  • Removed Guzzle\Http\ClientInterface::getCurlMulti(). This is a very specific implementation detail.
  • Removed Guzzle\Http\Message\RequestInterface::canCache. Use the CachePlugin.
  • Removed Guzzle\Http\Message\RequestInterface::setIsRedirect. Use the HistoryPlugin.
  • Removed Guzzle\Http\Message\RequestInterface::isRedirect. Use the HistoryPlugin.

Cache plugin breaking changes

  • CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a

CacheStorageInterface. These two objects and interface will be removed in a future version.

  • Always setting X-cache headers on cached responses
  • Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin
  • CacheStorageInterface::cache($key, Response $response, $ttl = null) has changed to `cache(RequestInterface

$request, Response $response);`

  • CacheStorageInterface::fetch($key) has changed to fetch(RequestInterface $request);
  • CacheStorageInterface::delete($key) has changed to delete(RequestInterface $request);
  • Added CacheStorageInterface::purge($url)
  • `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin

$plugin) has changed to DefaultRevalidation::__construct(CacheStorageInterface $cache, CanCacheStrategyInterface $canCache = null)`

  • Added RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)

3.5 to 3.6 ----------

  • Mixed casing of headers are now forced to be a single consistent casing across all values for that header.
  • Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution
  • Removed the whole changedHeader() function system of messages because all header changes now go through addHeader().

For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request.

  • Specific header implementations can be created for complex headers. When a message creates a header, it uses a

HeaderFactory which can map specific headers to specific header classes. There is now a Link header and CacheControl header implementation.

  • Moved getLinks() from Response to just be used on a Link header object.

If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the HeaderInterface (e.g. toArray(), getAll(), etc.).

Interface changes

  • Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate
  • Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti()
  • Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in

Guzzle\Http\Curl\RequestMediator

  • Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string.
  • Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface
  • Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders()

Removed deprecated functions

  • Removed Guzzle\Parser\ParserRegister::get(). Use getParser()
  • Removed Guzzle\Parser\ParserRegister::set(). Use registerParser().

Deprecations

  • The ability to case-insensitively search for header values
  • Guzzle\Http\Message\Header::hasExactHeader
  • Guzzle\Http\Message\Header::raw. Use getAll()
  • Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object

instead.

Other changes

  • All response header helper functions return a string rather than mixing Header objects and strings inconsistently
  • Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle

directly via interfaces

  • Removed the injecting of a request object onto a response object. The methods to get and set a request still exist

but are a no-op until removed.

  • Most classes that used to require a Guzzle\Service\Command\CommandInterface typehint now request a

Guzzle\Service\Command\ArrayCommandInterface.

  • Added Guzzle\Http\Message\RequestInterface::startResponse() to the RequestInterface to handle injecting a response

on a request while the request is still being transferred

  • Guzzle\Service\Command\CommandInterface now extends from ToArrayInterface and ArrayAccess

3.3 to 3.4 ----------

Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs.

3.2 to 3.3 ----------

Response::getEtag() quote stripping removed

Guzzle\Http\Message\Response::getEtag() no longer strips quotes around the ETag response header

Removed Guzzle\Http\Utils

The Guzzle\Http\Utils class was removed. This class was only used for testing.

Stream wrapper and type

Guzzle\Stream\Stream::getWrapper() and Guzzle\Stream\Stream::getStreamType() are no longer converted to lowercase.

curl.emit_io became emit_io

Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io'

3.1 to 3.2 ----------

CurlMulti is no longer reused globally

Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added to a single client can pollute requests dispatched from other clients.

If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the ServiceBuilder's service_builder.create_client event to inject a custom CurlMulti object into each client as it is created.

$multi = new Guzzle\Http\Curl\CurlMulti();
$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json');
$builder->addListener('service_builder.create_client', function ($event) use ($multi) {
    $event['client']->setCurlMulti($multi);
}
});

No default path

URLs no longer have a default path value of '/' if no path was specified.

Before:

$request = $client->get('http://www.foo.com');
echo $request->getUrl();
// >> http://www.foo.com/

After:

$request = $client->get('http://www.foo.com');
echo $request->getUrl();
// >> http://www.foo.com

Less verbose BadResponseException

The exception message for Guzzle\Http\Exception\BadResponseException no longer contains the full HTTP request and response information. You can, however, get access to the request and response object by calling getRequest() or getResponse() on the exception object.

Query parameter aggregation

Multi-valued query parameters are no longer aggregated using a callback function. Guzzle\Http\Query now has a setAggregator() method that accepts a Guzzle\Http\QueryAggregator\QueryAggregatorInterface object. This object is responsible for handling the aggregation of multi-valued query string variables into a flattened hash.

2.8 to 3.x ----------

Guzzle\Service\Inspector

Change \Guzzle\Service\Inspector::fromConfig to \Guzzle\Common\Collection::fromConfig

Before

use Guzzle\Service\Inspector;

class YourClient extends \Guzzle\Service\Client
{
    public static function factory($config = array())
    {
        $default = array();
        $required = array('base_url', 'username', 'api_key');
        $config = Inspector::fromConfig($config, $default, $required);

        $client = new self(
            $config->get('base_url'),
            $config->get('username'),
            $config->get('api_key')
        );
        $client->setConfig($config);

        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }

After

use Guzzle\Common\Collection;

class YourClient extends \Guzzle\Service\Client
{
    public static function factory($config = array())
    {
        $default = array();
        $required = array('base_url', 'username', 'api_key');
        $config = Collection::fromConfig($config, $default, $required);

        $client = new self(
            $config->get('base_url'),
            $config->get('username'),
            $config->get('api_key')
        );
        $client->setConfig($config);

        $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));

        return $client;
    }

Convert XML Service Descriptions to JSON

Before

<?xml version="1.0" encoding="UTF-8"?>
<client>
    <commands>
        <!-- Groups -->
        <command name="list_groups" method="GET" uri="groups.json">
            <doc>Get a list of groups</doc>
        </command>
        <command name="search_groups" method="GET" uri='search.json?query="{{query}} type:group"'>
            <doc>Uses a search query to get a list of groups</doc>
            <param name="query" type="string" required="true" />
        </command>
        <command name="create_group" method="POST" uri="groups.json">
            <doc>Create a group</doc>
            <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
            <param name="Content-Type" location="header" static="application/json"/>
        </command>
        <command name="delete_group" method="DELETE" uri="groups/{{id}}.json">
            <doc>Delete a group by ID</doc>
            <param name="id" type="integer" required="true"/>
        </command>
        <command name="get_group" method="GET" uri="groups/{{id}}.json">
            <param name="id" type="integer" required="true"/>
        </command>
        <command name="update_group" method="PUT" uri="groups/{{id}}.json">
            <doc>Update a group</doc>
            <param name="id" type="integer" required="true"/>
            <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
            <param name="Content-Type" location="header" static="application/json"/>
        </command>
    </commands>
</client>

After

{
    "name":       "Zendesk REST API v2",
    "apiVersion": "2012-12-31",
    "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users",
    "operations": {
        "list_groups":  {
            "httpMethod":"GET",
            "uri":       "groups.json",
            "summary":   "Get a list of groups"
        },
        "search_groups":{
            "httpMethod":"GET",
            "uri":       "search.json?query=\"{query} type:group\"",
            "summary":   "Uses a search query to get a list of groups",
            "parameters":{
                "query":{
                    "location":   "uri",
                    "description":"Zendesk Search Query",
                    "type":       "string",
                    "required":   true
                }
            }
        },
        "create_group": {
            "httpMethod":"POST",
            "uri":       "groups.json",
            "summary":   "Create a group",
            "parameters":{
                "data":        {
                    "type":       "array",
                    "location":   "body",
                    "description":"Group JSON",
                    "filters":    "json_encode",
                    "required":   true
                },
                "Content-Type":{
                    "type":    "string",
                    "location":"header",
                    "static":  "application/json"
                }
            }
        },
        "delete_group": {
            "httpMethod":"DELETE",
            "uri":       "groups/{id}.json",
            "summary":   "Delete a group",
            "parameters":{
                "id":{
                    "location":   "uri",
                    "description":"Group to delete by ID",
                    "type":       "integer",
                    "required":   true
                }
            }
        },
        "get_group":    {
            "httpMethod":"GET",
            "uri":       "groups/{id}.json",
            "summary":   "Get a ticket",
            "parameters":{
                "id":{
                    "location":   "uri",
                    "description":"Group to get by ID",
                    "type":       "integer",
                    "required":   true
                }
            }
        },
        "update_group": {
            "httpMethod":"PUT",
            "uri":       "groups/{id}.json",
            "summary":   "Update a group",
            "parameters":{
                "id":          {
                    "location":   "uri",
                    "description":"Group to update by ID",
                    "type":       "integer",
                    "required":   true
                },
                "data":        {
                    "type":       "array",
                    "location":   "body",
                    "description":"Group JSON",
                    "filters":    "json_encode",
                    "required":   true
                },
                "Content-Type":{
                    "type":    "string",
                    "location":"header",
                    "static":  "application/json"
                }
            }
        }
}

Guzzle\Service\Description\ServiceDescription

Commands are now called Operations

Before

use Guzzle\Service\Description\ServiceDescription;

$sd = new ServiceDescription();
$sd->getCommands();     // @returns ApiCommandInterface[]
$sd->hasCommand($name);
$sd->getCommand($name); // @returns ApiCommandInterface|null
$sd->addCommand($command); // @param ApiCommandInterface $command

After

use Guzzle\Service\Description\ServiceDescription;

$sd = new ServiceDescription();
$sd->getOperations();           // @returns OperationInterface[]
$sd->hasOperation($name);
$sd->getOperation($name);       // @returns OperationInterface|null
$sd->addOperation($operation);  // @param OperationInterface $operation

Guzzle\Common\Inflection\Inflector

Namespace is now Guzzle\Inflection\Inflector

Guzzle\Http\Plugin

Namespace is now Guzzle\Plugin. Many other changes occur within this namespace and are detailed in their own sections below.

Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log

Now Guzzle\Plugin\Log\LogPlugin and Guzzle\Log respectively.

Before

use Guzzle\Common\Log\ClosureLogAdapter;
use Guzzle\Http\Plugin\LogPlugin;

/** @var \Guzzle\Http\Client */
$client;

// $verbosity is an integer indicating desired message verbosity level
$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE);

After

use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Log\MessageFormatter;
use Guzzle\Plugin\Log\LogPlugin;

/** @var \Guzzle\Http\Client */
$client;

// $format is a string indicating desired message format -- @see MessageFormatter
$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT);

Guzzle\Http\Plugin\CurlAuthPlugin

Now Guzzle\Plugin\CurlAuth\CurlAuthPlugin.

Guzzle\Http\Plugin\ExponentialBackoffPlugin

Now Guzzle\Plugin\Backoff\BackoffPlugin, and other changes.

Before

use Guzzle\Http\Plugin\ExponentialBackoffPlugin;

$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge(
        ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429)
    ));

$client->addSubscriber($backoffPlugin);

After

use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;

// Use convenient factory method instead -- see implementation for ideas of what
// you can do with chaining backoff strategies
$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge(
        HttpBackoffStrategy::getDefaultFailureCodes(), array(429)
    ));
$client->addSubscriber($backoffPlugin);

Known Issues

[BUG] Accept-Encoding header behavior changed unintentionally.

(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e)

In version 2.8 setting the Accept-Encoding header would set the CURLOPT_ENCODING option, which permitted cURL to properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. See issue #217 for a workaround, or use a version containing the fix.

Source
1Guzzle Upgrade Guide
2====================
3
46.0 to 7.0
5----------
6
7In order to take advantage of the new features of PHP, Guzzle dropped the support
8of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return
9types for functions and methods have been added wherever possible.
10
11Please make sure:
12- You are calling a function or a method with the correct type.
13- If you extend a class of Guzzle; update all signatures on methods you override.
14
15#### Other Backwards Compatibility Breaking Changes
16
17- Class `GuzzleHttp\UriTemplate` is removed.
18- Class `GuzzleHttp\Exception\SeekException` is removed.
19- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`,
20 `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty
21 Response as argument.
22- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException`
23 instead of `GuzzleHttp\Exception\RequestException`.
24- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed.
25- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed.
26- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead.
27- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed.
28 Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative.
29- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed.
30- Request option `exceptions` is removed. Please use `http_errors`.
31- Request option `save_to` is removed. Please use `sink`.
32- Pool option `pool_size` is removed. Please use `concurrency`.
33- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility.
34- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation.
35- The `log` middleware will log the errors with level `error` instead of `notice`
36- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher).
37
38#### Native Functions Calls
39
40All internal native functions calls of Guzzle are now prefixed with a slash. This
41change makes it impossible for method overloading by other libraries or applications.
42Example:
43
44```php
45// Before:
46curl_version();
47
48// After:
49\curl_version();
50```
51
52For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..7.0.0).
53
545.0 to 6.0
55----------
56
57Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages.
58Due to the fact that these messages are immutable, this prompted a refactoring
59of Guzzle to use a middleware based system rather than an event system. Any
60HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be
61updated to work with the new immutable PSR-7 request and response objects. Any
62event listeners or subscribers need to be updated to become middleware
63functions that wrap handlers (or are injected into a
64`GuzzleHttp\HandlerStack`).
65
66- Removed `GuzzleHttp\BatchResults`
67- Removed `GuzzleHttp\Collection`
68- Removed `GuzzleHttp\HasDataTrait`
69- Removed `GuzzleHttp\ToArrayInterface`
70- The `guzzlehttp/streams` dependency has been removed. Stream functionality
71 is now present in the `GuzzleHttp\Psr7` namespace provided by the
72 `guzzlehttp/psr7` package.
73- Guzzle no longer uses ReactPHP promises and now uses the
74 `guzzlehttp/promises` library. We use a custom promise library for three
75 significant reasons:
76 1. React promises (at the time of writing this) are recursive. Promise
77 chaining and promise resolution will eventually blow the stack. Guzzle
78 promises are not recursive as they use a sort of trampolining technique.
79 Note: there has been movement in the React project to modify promises to
80 no longer utilize recursion.
81 2. Guzzle needs to have the ability to synchronously block on a promise to
82 wait for a result. Guzzle promises allows this functionality (and does
83 not require the use of recursion).
84 3. Because we need to be able to wait on a result, doing so using React
85 promises requires wrapping react promises with RingPHP futures. This
86 overhead is no longer needed, reducing stack sizes, reducing complexity,
87 and improving performance.
88- `GuzzleHttp\Mimetypes` has been moved to a function in
89 `GuzzleHttp\Psr7\mimetype_from_extension` and
90 `GuzzleHttp\Psr7\mimetype_from_filename`.
91- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query
92 strings must now be passed into request objects as strings, or provided to
93 the `query` request option when creating requests with clients. The `query`
94 option uses PHP's `http_build_query` to convert an array to a string. If you
95 need a different serialization technique, you will need to pass the query
96 string in as a string. There are a couple helper functions that will make
97 working with query strings easier: `GuzzleHttp\Psr7\parse_query` and
98 `GuzzleHttp\Psr7\build_query`.
99- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware
100 system based on PSR-7, using RingPHP and it's middleware system as well adds
101 more complexity than the benefits it provides. All HTTP handlers that were
102 present in RingPHP have been modified to work directly with PSR-7 messages
103 and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces
104 complexity in Guzzle, removes a dependency, and improves performance. RingPHP
105 will be maintained for Guzzle 5 support, but will no longer be a part of
106 Guzzle 6.
107- As Guzzle now uses a middleware based systems the event system and RingPHP
108 integration has been removed. Note: while the event system has been removed,
109 it is possible to add your own type of event system that is powered by the
110 middleware system.
111 - Removed the `Event` namespace.
112 - Removed the `Subscriber` namespace.
113 - Removed `Transaction` class
114 - Removed `RequestFsm`
115 - Removed `RingBridge`
116 - `GuzzleHttp\Subscriber\Cookie` is now provided by
117 `GuzzleHttp\Middleware::cookies`
118 - `GuzzleHttp\Subscriber\HttpError` is now provided by
119 `GuzzleHttp\Middleware::httpError`
120 - `GuzzleHttp\Subscriber\History` is now provided by
121 `GuzzleHttp\Middleware::history`
122 - `GuzzleHttp\Subscriber\Mock` is now provided by
123 `GuzzleHttp\Handler\MockHandler`
124 - `GuzzleHttp\Subscriber\Prepare` is now provided by
125 `GuzzleHttp\PrepareBodyMiddleware`
126 - `GuzzleHttp\Subscriber\Redirect` is now provided by
127 `GuzzleHttp\RedirectMiddleware`
128- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in
129 `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone.
130- Static functions in `GuzzleHttp\Utils` have been moved to namespaced
131 functions under the `GuzzleHttp` namespace. This requires either a Composer
132 based autoloader or you to include functions.php.
133- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to
134 `GuzzleHttp\ClientInterface::getConfig`.
135- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed.
136- The `json` and `xml` methods of response objects has been removed. With the
137 migration to strictly adhering to PSR-7 as the interface for Guzzle messages,
138 adding methods to message interfaces would actually require Guzzle messages
139 to extend from PSR-7 messages rather then work with them directly.
140
141## Migrating to middleware
142
143The change to PSR-7 unfortunately required significant refactoring to Guzzle
144due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event
145system from plugins. The event system relied on mutability of HTTP messages and
146side effects in order to work. With immutable messages, you have to change your
147workflow to become more about either returning a value (e.g., functional
148middlewares) or setting a value on an object. Guzzle v6 has chosen the
149functional middleware approach.
150
151Instead of using the event system to listen for things like the `before` event,
152you now create a stack based middleware function that intercepts a request on
153the way in and the promise of the response on the way out. This is a much
154simpler and more predictable approach than the event system and works nicely
155with PSR-7 middleware. Due to the use of promises, the middleware system is
156also asynchronous.
157
158v5:
159
160```php
161use GuzzleHttp\Event\BeforeEvent;
162$client = new GuzzleHttp\Client();
163// Get the emitter and listen to the before event.
164$client->getEmitter()->on('before', function (BeforeEvent $e) {
165 // Guzzle v5 events relied on mutation
166 $e->getRequest()->setHeader('X-Foo', 'Bar');
167});
168```
169
170v6:
171
172In v6, you can modify the request before it is sent using the `mapRequest`
173middleware. The idiomatic way in v6 to modify the request/response lifecycle is
174to setup a handler middleware stack up front and inject the handler into a
175client.
176
177```php
178use GuzzleHttp\Middleware;
179// Create a handler stack that has all of the default middlewares attached
180$handler = GuzzleHttp\HandlerStack::create();
181// Push the handler onto the handler stack
182$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
183 // Notice that we have to return a request object
184 return $request->withHeader('X-Foo', 'Bar');
185}));
186// Inject the handler into the client
187$client = new GuzzleHttp\Client(['handler' => $handler]);
188```
189
190## POST Requests
191
192This version added the [`form_params`](https://github.com/guzzle/guzzle/blob/6.5/docs/request-options.rst#form_params)
193and `multipart` request options. `form_params` is an associative array of
194strings or array of strings and is used to serialize an
195`application/x-www-form-urlencoded` POST request. The
196[`multipart`](https://github.com/guzzle/guzzle/blob/6.5/docs/request-options.rst#multipart)
197option is now used to send a multipart/form-data POST request.
198
199`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add
200POST files to a multipart/form-data request.
201
202The `body` option no longer accepts an array to send POST requests. Please use
203`multipart` or `form_params` instead.
204
205The `base_url` option has been renamed to `base_uri`.
206
2074.x to 5.0
208----------
209
210## Rewritten Adapter Layer
211
212Guzzle now uses [RingPHP](https://github.com/guzzle/RingPHP) to send
213HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor
214is still supported, but it has now been renamed to `handler`. Instead of
215passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP
216`callable` that follows the RingPHP specification.
217
218## Removed Fluent Interfaces
219
220[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/)
221from the following classes:
222
223- `GuzzleHttp\Collection`
224- `GuzzleHttp\Url`
225- `GuzzleHttp\Query`
226- `GuzzleHttp\Post\PostBody`
227- `GuzzleHttp\Cookie\SetCookie`
228
229## Removed functions.php
230
231Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following
232functions can be used as replacements.
233
234- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode`
235- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath`
236- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path`
237- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however,
238 deprecated in favor of using `GuzzleHttp\Pool::batch()`.
239
240The "procedural" global client has been removed with no replacement (e.g.,
241`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client`
242object as a replacement.
243
244## `throwImmediately` has been removed
245
246The concept of "throwImmediately" has been removed from exceptions and error
247events. This control mechanism was used to stop a transfer of concurrent
248requests from completing. This can now be handled by throwing the exception or
249by cancelling a pool of requests or each outstanding future request
250individually.
251
252## headers event has been removed
253
254Removed the "headers" event. This event was only useful for changing the
255body a response once the headers of the response were known. You can implement
256a similar behavior in a number of ways. One example might be to use a
257FnStream that has access to the transaction being sent. For example, when the
258first byte is written, you could check if the response headers match your
259expectations, and if so, change the actual stream body that is being
260written to.
261
262## Updates to HTTP Messages
263
264Removed the `asArray` parameter from
265`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header
266value as an array, then use the newly added `getHeaderAsArray()` method of
267`MessageInterface`. This change makes the Guzzle interfaces compatible with
268the PSR-7 interfaces.
269
2703.x to 4.0
271----------
272
273## Overarching changes:
274
275- Now requires PHP 5.4 or greater.
276- No longer requires cURL to send requests.
277- Guzzle no longer wraps every exception it throws. Only exceptions that are
278 recoverable are now wrapped by Guzzle.
279- Various namespaces have been removed or renamed.
280- No longer requiring the Symfony EventDispatcher. A custom event dispatcher
281 based on the Symfony EventDispatcher is
282 now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant
283 speed and functionality improvements).
284
285Changes per Guzzle 3.x namespace are described below.
286
287## Batch
288
289The `Guzzle\Batch` namespace has been removed. This is best left to
290third-parties to implement on top of Guzzle's core HTTP library.
291
292## Cache
293
294The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement
295has been implemented yet, but hoping to utilize a PSR cache interface).
296
297## Common
298
299- Removed all of the wrapped exceptions. It's better to use the standard PHP
300 library for unrecoverable exceptions.
301- `FromConfigInterface` has been removed.
302- `Guzzle\Common\Version` has been removed. The VERSION constant can be found
303 at `GuzzleHttp\ClientInterface::VERSION`.
304
305### Collection
306
307- `getAll` has been removed. Use `toArray` to convert a collection to an array.
308- `inject` has been removed.
309- `keySearch` has been removed.
310- `getPath` no longer supports wildcard expressions. Use something better like
311 JMESPath for this.
312- `setPath` now supports appending to an existing array via the `[]` notation.
313
314### Events
315
316Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses
317`GuzzleHttp\Event\Emitter`.
318
319- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by
320 `GuzzleHttp\Event\EmitterInterface`.
321- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by
322 `GuzzleHttp\Event\Emitter`.
323- `Symfony\Component\EventDispatcher\Event` is replaced by
324 `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in
325 `GuzzleHttp\Event\EventInterface`.
326- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and
327 `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the
328 event emitter of a request, client, etc. now uses the `getEmitter` method
329 rather than the `getDispatcher` method.
330
331#### Emitter
332
333- Use the `once()` method to add a listener that automatically removes itself
334 the first time it is invoked.
335- Use the `listeners()` method to retrieve a list of event listeners rather than
336 the `getListeners()` method.
337- Use `emit()` instead of `dispatch()` to emit an event from an emitter.
338- Use `attach()` instead of `addSubscriber()` and `detach()` instead of
339 `removeSubscriber()`.
340
341```php
342$mock = new Mock();
343// 3.x
344$request->getEventDispatcher()->addSubscriber($mock);
345$request->getEventDispatcher()->removeSubscriber($mock);
346// 4.x
347$request->getEmitter()->attach($mock);
348$request->getEmitter()->detach($mock);
349```
350
351Use the `on()` method to add a listener rather than the `addListener()` method.
352
353```php
354// 3.x
355$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } );
356// 4.x
357$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } );
358```
359
360## Http
361
362### General changes
363
364- The cacert.pem certificate has been moved to `src/cacert.pem`.
365- Added the concept of adapters that are used to transfer requests over the
366 wire.
367- Simplified the event system.
368- Sending requests in parallel is still possible, but batching is no longer a
369 concept of the HTTP layer. Instead, you must use the `complete` and `error`
370 events to asynchronously manage parallel request transfers.
371- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`.
372- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`.
373- QueryAggregators have been rewritten so that they are simply callable
374 functions.
375- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in
376 `functions.php` for an easy to use static client instance.
377- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from
378 `GuzzleHttp\Exception\TransferException`.
379
380### Client
381
382Calling methods like `get()`, `post()`, `head()`, etc. no longer create and
383return a request, but rather creates a request, sends the request, and returns
384the response.
385
386```php
387// 3.0
388$request = $client->get('/');
389$response = $request->send();
390
391// 4.0
392$response = $client->get('/');
393
394// or, to mirror the previous behavior
395$request = $client->createRequest('GET', '/');
396$response = $client->send($request);
397```
398
399`GuzzleHttp\ClientInterface` has changed.
400
401- The `send` method no longer accepts more than one request. Use `sendAll` to
402 send multiple requests in parallel.
403- `setUserAgent()` has been removed. Use a default request option instead. You
404 could, for example, do something like:
405 `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`.
406- `setSslVerification()` has been removed. Use default request options instead,
407 like `$client->setConfig('defaults/verify', true)`.
408
409`GuzzleHttp\Client` has changed.
410
411- The constructor now accepts only an associative array. You can include a
412 `base_url` string or array to use a URI template as the base URL of a client.
413 You can also specify a `defaults` key that is an associative array of default
414 request options. You can pass an `adapter` to use a custom adapter,
415 `batch_adapter` to use a custom adapter for sending requests in parallel, or
416 a `message_factory` to change the factory used to create HTTP requests and
417 responses.
418- The client no longer emits a `client.create_request` event.
419- Creating requests with a client no longer automatically utilize a URI
420 template. You must pass an array into a creational method (e.g.,
421 `createRequest`, `get`, `put`, etc.) in order to expand a URI template.
422
423### Messages
424
425Messages no longer have references to their counterparts (i.e., a request no
426longer has a reference to it's response, and a response no loger has a
427reference to its request). This association is now managed through a
428`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to
429these transaction objects using request events that are emitted over the
430lifecycle of a request.
431
432#### Requests with a body
433
434- `GuzzleHttp\Message\EntityEnclosingRequest` and
435 `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The
436 separation between requests that contain a body and requests that do not
437 contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface`
438 handles both use cases.
439- Any method that previously accepts a `GuzzleHttp\Response` object now accept a
440 `GuzzleHttp\Message\ResponseInterface`.
441- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to
442 `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create
443 both requests and responses and is implemented in
444 `GuzzleHttp\Message\MessageFactory`.
445- POST field and file methods have been removed from the request object. You
446 must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface`
447 to control the format of a POST body. Requests that are created using a
448 standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use
449 a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if
450 the method is POST and no body is provided.
451
452```php
453$request = $client->createRequest('POST', '/');
454$request->getBody()->setField('foo', 'bar');
455$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r')));
456```
457
458#### Headers
459
460- `GuzzleHttp\Message\Header` has been removed. Header values are now simply
461 represented by an array of values or as a string. Header values are returned
462 as a string by default when retrieving a header value from a message. You can
463 pass an optional argument of `true` to retrieve a header value as an array
464 of strings instead of a single concatenated string.
465- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to
466 `GuzzleHttp\Post`. This interface has been simplified and now allows the
467 addition of arbitrary headers.
468- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most
469 of the custom headers are now handled separately in specific
470 subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has
471 been updated to properly handle headers that contain parameters (like the
472 `Link` header).
473
474#### Responses
475
476- `GuzzleHttp\Message\Response::getInfo()` and
477 `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event
478 system to retrieve this type of information.
479- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed.
480- `GuzzleHttp\Message\Response::getMessage()` has been removed.
481- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific
482 methods have moved to the CacheSubscriber.
483- Header specific helper functions like `getContentMd5()` have been removed.
484 Just use `getHeader('Content-MD5')` instead.
485- `GuzzleHttp\Message\Response::setRequest()` and
486 `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event
487 system to work with request and response objects as a transaction.
488- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the
489 Redirect subscriber instead.
490- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have
491 been removed. Use `getStatusCode()` instead.
492
493#### Streaming responses
494
495Streaming requests can now be created by a client directly, returning a
496`GuzzleHttp\Message\ResponseInterface` object that contains a body stream
497referencing an open PHP HTTP stream.
498
499```php
500// 3.0
501use Guzzle\Stream\PhpStreamRequestFactory;
502$request = $client->get('/');
503$factory = new PhpStreamRequestFactory();
504$stream = $factory->fromRequest($request);
505$data = $stream->read(1024);
506
507// 4.0
508$response = $client->get('/', ['stream' => true]);
509// Read some data off of the stream in the response body
510$data = $response->getBody()->read(1024);
511```
512
513#### Redirects
514
515The `configureRedirects()` method has been removed in favor of a
516`allow_redirects` request option.
517
518```php
519// Standard redirects with a default of a max of 5 redirects
520$request = $client->createRequest('GET', '/', ['allow_redirects' => true]);
521
522// Strict redirects with a custom number of redirects
523$request = $client->createRequest('GET', '/', [
524 'allow_redirects' => ['max' => 5, 'strict' => true]
525]);
526```
527
528#### EntityBody
529
530EntityBody interfaces and classes have been removed or moved to
531`GuzzleHttp\Stream`. All classes and interfaces that once required
532`GuzzleHttp\EntityBodyInterface` now require
533`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no
534longer uses `GuzzleHttp\EntityBody::factory` but now uses
535`GuzzleHttp\Stream\Stream::factory` or even better:
536`GuzzleHttp\Stream\create()`.
537
538- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface`
539- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream`
540- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream`
541- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream`
542- `Guzzle\Http\IoEmittyinEntityBody` has been removed.
543
544#### Request lifecycle events
545
546Requests previously submitted a large number of requests. The number of events
547emitted over the lifecycle of a request has been significantly reduced to make
548it easier to understand how to extend the behavior of a request. All events
549emitted during the lifecycle of a request now emit a custom
550`GuzzleHttp\Event\EventInterface` object that contains context providing
551methods and a way in which to modify the transaction at that specific point in
552time (e.g., intercept the request and set a response on the transaction).
553
554- `request.before_send` has been renamed to `before` and now emits a
555 `GuzzleHttp\Event\BeforeEvent`
556- `request.complete` has been renamed to `complete` and now emits a
557 `GuzzleHttp\Event\CompleteEvent`.
558- `request.sent` has been removed. Use `complete`.
559- `request.success` has been removed. Use `complete`.
560- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`.
561- `request.exception` has been removed. Use `error`.
562- `request.receive.status_line` has been removed.
563- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to
564 maintain a status update.
565- `curl.callback.write` has been removed. Use a custom `StreamInterface` to
566 intercept writes.
567- `curl.callback.read` has been removed. Use a custom `StreamInterface` to
568 intercept reads.
569
570`headers` is a new event that is emitted after the response headers of a
571request have been received before the body of the response is downloaded. This
572event emits a `GuzzleHttp\Event\HeadersEvent`.
573
574You can intercept a request and inject a response using the `intercept()` event
575of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and
576`GuzzleHttp\Event\ErrorEvent` event.
577
578## Inflection
579
580The `Guzzle\Inflection` namespace has been removed. This is not a core concern
581of Guzzle.
582
583## Iterator
584
585The `Guzzle\Iterator` namespace has been removed.
586
587- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and
588 `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of
589 Guzzle itself.
590- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent
591 class is shipped with PHP 5.4.
592- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because
593 it's easier to just wrap an iterator in a generator that maps values.
594
595For a replacement of these iterators, see https://github.com/nikic/iter
596
597## Log
598
599The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The
600`Guzzle\Log` namespace has been removed. Guzzle now relies on
601`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been
602moved to `GuzzleHttp\Subscriber\Log\Formatter`.
603
604## Parser
605
606The `Guzzle\Parser` namespace has been removed. This was previously used to
607make it possible to plug in custom parsers for cookies, messages, URI
608templates, and URLs; however, this level of complexity is not needed in Guzzle
609so it has been removed.
610
611- Cookie: Cookie parsing logic has been moved to
612 `GuzzleHttp\Cookie\SetCookie::fromString`.
613- Message: Message parsing logic for both requests and responses has been moved
614 to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only
615 used in debugging or deserializing messages, so it doesn't make sense for
616 Guzzle as a library to add this level of complexity to parsing messages.
617- UriTemplate: URI template parsing has been moved to
618 `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL
619 URI template library if it is installed.
620- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously
621 it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary,
622 then developers are free to subclass `GuzzleHttp\Url`.
623
624## Plugin
625
626The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`.
627Several plugins are shipping with the core Guzzle library under this namespace.
628
629- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar
630 code has moved to `GuzzleHttp\Cookie`.
631- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin.
632- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is
633 received.
634- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin.
635- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before
636 sending. This subscriber is attached to all requests by default.
637- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin.
638
639The following plugins have been removed (third-parties are free to re-implement
640these if needed):
641
642- `GuzzleHttp\Plugin\Async` has been removed.
643- `GuzzleHttp\Plugin\CurlAuth` has been removed.
644- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This
645 functionality should instead be implemented with event listeners that occur
646 after normal response parsing occurs in the guzzle/command package.
647
648The following plugins are not part of the core Guzzle package, but are provided
649in separate repositories:
650
651- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler
652 to build custom retry policies using simple functions rather than various
653 chained classes. See: https://github.com/guzzle/retry-subscriber
654- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to
655 https://github.com/guzzle/cache-subscriber
656- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to
657 https://github.com/guzzle/log-subscriber
658- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to
659 https://github.com/guzzle/message-integrity-subscriber
660- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to
661 `GuzzleHttp\Subscriber\MockSubscriber`.
662- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to
663 https://github.com/guzzle/oauth-subscriber
664
665## Service
666
667The service description layer of Guzzle has moved into two separate packages:
668
669- https://github.com/guzzle/command Provides a high level abstraction over web
670 services by representing web service operations using commands.
671- https://github.com/guzzle/guzzle-services Provides an implementation of
672 guzzle/command that provides request serialization and response parsing using
673 Guzzle service descriptions.
674
675## Stream
676
677Stream have moved to a separate package available at
678https://github.com/guzzle/streams.
679
680`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take
681on the responsibilities of `Guzzle\Http\EntityBody` and
682`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number
683of methods implemented by the `StreamInterface` has been drastically reduced to
684allow developers to more easily extend and decorate stream behavior.
685
686## Removed methods from StreamInterface
687
688- `getStream` and `setStream` have been removed to better encapsulate streams.
689- `getMetadata` and `setMetadata` have been removed in favor of
690 `GuzzleHttp\Stream\MetadataStreamInterface`.
691- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been
692 removed. This data is accessible when
693 using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`.
694- `rewind` has been removed. Use `seek(0)` for a similar behavior.
695
696## Renamed methods
697
698- `detachStream` has been renamed to `detach`.
699- `feof` has been renamed to `eof`.
700- `ftell` has been renamed to `tell`.
701- `readLine` has moved from an instance method to a static class method of
702 `GuzzleHttp\Stream\Stream`.
703
704## Metadata streams
705
706`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams
707that contain additional metadata accessible via `getMetadata()`.
708`GuzzleHttp\Stream\StreamInterface::getMetadata` and
709`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed.
710
711## StreamRequestFactory
712
713The entire concept of the StreamRequestFactory has been removed. The way this
714was used in Guzzle 3 broke the actual interface of sending streaming requests
715(instead of getting back a Response, you got a StreamInterface). Streaming
716PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`.
717
7183.6 to 3.7
719----------
720
721### Deprecations
722
723- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.:
724
725```php
726\Guzzle\Common\Version::$emitWarnings = true;
727```
728
729The following APIs and options have been marked as deprecated:
730
731- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead.
732- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
733- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
734- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead.
735- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead.
736- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated
737- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client.
738- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8.
739- Marked `Guzzle\Common\Collection::inject()` as deprecated.
740- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use
741 `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or
742 `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));`
743
7443.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational
745request methods. When paired with a client's configuration settings, these options allow you to specify default settings
746for various aspects of a request. Because these options make other previous configuration options redundant, several
747configuration options and methods of a client and AbstractCommand have been deprecated.
748
749- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`.
750- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`.
751- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')`
752- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0
753
754 $command = $client->getCommand('foo', array(
755 'command.headers' => array('Test' => '123'),
756 'command.response_body' => '/path/to/file'
757 ));
758
759 // Should be changed to:
760
761 $command = $client->getCommand('foo', array(
762 'command.request_options' => array(
763 'headers' => array('Test' => '123'),
764 'save_as' => '/path/to/file'
765 )
766 ));
767
768### Interface changes
769
770Additions and changes (you will need to update any implementations or subclasses you may have created):
771
772- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`:
773 createRequest, head, delete, put, patch, post, options, prepareRequest
774- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()`
775- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface`
776- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to
777 `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a
778 resource, string, or EntityBody into the $options parameter to specify the download location of the response.
779- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a
780 default `array()`
781- Added `Guzzle\Stream\StreamInterface::isRepeatable`
782- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods.
783
784The following methods were removed from interfaces. All of these methods are still available in the concrete classes
785that implement them, but you should update your code to use alternative methods:
786
787- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use
788 `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or
789 `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or
790 `$client->setDefaultOption('headers/{header_name}', 'value')`. or
791 `$client->setDefaultOption('headers', array('header_name' => 'value'))`.
792- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`.
793- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail.
794- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail.
795- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail.
796- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin.
797- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin.
798- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin.
799
800### Cache plugin breaking changes
801
802- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a
803 CacheStorageInterface. These two objects and interface will be removed in a future version.
804- Always setting X-cache headers on cached responses
805- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin
806- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface
807 $request, Response $response);`
808- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);`
809- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);`
810- Added `CacheStorageInterface::purge($url)`
811- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin
812 $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache,
813 CanCacheStrategyInterface $canCache = null)`
814- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)`
815
8163.5 to 3.6
817----------
818
819* Mixed casing of headers are now forced to be a single consistent casing across all values for that header.
820* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution
821* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader().
822 For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader().
823 Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request.
824* Specific header implementations can be created for complex headers. When a message creates a header, it uses a
825 HeaderFactory which can map specific headers to specific header classes. There is now a Link header and
826 CacheControl header implementation.
827* Moved getLinks() from Response to just be used on a Link header object.
828
829If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the
830HeaderInterface (e.g. toArray(), getAll(), etc.).
831
832### Interface changes
833
834* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate
835* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti()
836* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in
837 Guzzle\Http\Curl\RequestMediator
838* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string.
839* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface
840* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders()
841
842### Removed deprecated functions
843
844* Removed Guzzle\Parser\ParserRegister::get(). Use getParser()
845* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser().
846
847### Deprecations
848
849* The ability to case-insensitively search for header values
850* Guzzle\Http\Message\Header::hasExactHeader
851* Guzzle\Http\Message\Header::raw. Use getAll()
852* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object
853 instead.
854
855### Other changes
856
857* All response header helper functions return a string rather than mixing Header objects and strings inconsistently
858* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle
859 directly via interfaces
860* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist
861 but are a no-op until removed.
862* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a
863 `Guzzle\Service\Command\ArrayCommandInterface`.
864* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response
865 on a request while the request is still being transferred
866* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess
867
8683.3 to 3.4
869----------
870
871Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs.
872
8733.2 to 3.3
874----------
875
876### Response::getEtag() quote stripping removed
877
878`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header
879
880### Removed `Guzzle\Http\Utils`
881
882The `Guzzle\Http\Utils` class was removed. This class was only used for testing.
883
884### Stream wrapper and type
885
886`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase.
887
888### curl.emit_io became emit_io
889
890Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the
891'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io'
892
8933.1 to 3.2
894----------
895
896### CurlMulti is no longer reused globally
897
898Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added
899to a single client can pollute requests dispatched from other clients.
900
901If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the
902ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is
903created.
904
905```php
906$multi = new Guzzle\Http\Curl\CurlMulti();
907$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json');
908$builder->addListener('service_builder.create_client', function ($event) use ($multi) {
909 $event['client']->setCurlMulti($multi);
910}
911});
912```
913
914### No default path
915
916URLs no longer have a default path value of '/' if no path was specified.
917
918Before:
919
920```php
921$request = $client->get('http://www.foo.com');
922echo $request->getUrl();
923// >> http://www.foo.com/
924```
925
926After:
927
928```php
929$request = $client->get('http://www.foo.com');
930echo $request->getUrl();
931// >> http://www.foo.com
932```
933
934### Less verbose BadResponseException
935
936The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and
937response information. You can, however, get access to the request and response object by calling `getRequest()` or
938`getResponse()` on the exception object.
939
940### Query parameter aggregation
941
942Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a
943setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is
944responsible for handling the aggregation of multi-valued query string variables into a flattened hash.
945
9462.8 to 3.x
947----------
948
949### Guzzle\Service\Inspector
950
951Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig`
952
953**Before**
954
955```php
956use Guzzle\Service\Inspector;
957
958class YourClient extends \Guzzle\Service\Client
959{
960 public static function factory($config = array())
961 {
962 $default = array();
963 $required = array('base_url', 'username', 'api_key');
964 $config = Inspector::fromConfig($config, $default, $required);
965
966 $client = new self(
967 $config->get('base_url'),
968 $config->get('username'),
969 $config->get('api_key')
970 );
971 $client->setConfig($config);
972
973 $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));
974
975 return $client;
976 }
977```
978
979**After**
980
981```php
982use Guzzle\Common\Collection;
983
984class YourClient extends \Guzzle\Service\Client
985{
986 public static function factory($config = array())
987 {
988 $default = array();
989 $required = array('base_url', 'username', 'api_key');
990 $config = Collection::fromConfig($config, $default, $required);
991
992 $client = new self(
993 $config->get('base_url'),
994 $config->get('username'),
995 $config->get('api_key')
996 );
997 $client->setConfig($config);
998
999 $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json'));
1000
1001 return $client;
1002 }
1003```
1004
1005### Convert XML Service Descriptions to JSON
1006
1007**Before**
1008
1009```xml
1010<?xml version="1.0" encoding="UTF-8"?>
1011<client>
1012 <commands>
1013 <!-- Groups -->
1014 <command name="list_groups" method="GET" uri="groups.json">
1015 <doc>Get a list of groups</doc>
1016 </command>
1017 <command name="search_groups" method="GET" uri='search.json?query="{{query}} type:group"'>
1018 <doc>Uses a search query to get a list of groups</doc>
1019 <param name="query" type="string" required="true" />
1020 </command>
1021 <command name="create_group" method="POST" uri="groups.json">
1022 <doc>Create a group</doc>
1023 <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
1024 <param name="Content-Type" location="header" static="application/json"/>
1025 </command>
1026 <command name="delete_group" method="DELETE" uri="groups/{{id}}.json">
1027 <doc>Delete a group by ID</doc>
1028 <param name="id" type="integer" required="true"/>
1029 </command>
1030 <command name="get_group" method="GET" uri="groups/{{id}}.json">
1031 <param name="id" type="integer" required="true"/>
1032 </command>
1033 <command name="update_group" method="PUT" uri="groups/{{id}}.json">
1034 <doc>Update a group</doc>
1035 <param name="id" type="integer" required="true"/>
1036 <param name="data" type="array" location="body" filters="json_encode" doc="Group JSON"/>
1037 <param name="Content-Type" location="header" static="application/json"/>
1038 </command>
1039 </commands>
1040</client>
1041```
1042
1043**After**
1044
1045```json
1046{
1047 "name": "Zendesk REST API v2",
1048 "apiVersion": "2012-12-31",
1049 "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users",
1050 "operations": {
1051 "list_groups": {
1052 "httpMethod":"GET",
1053 "uri": "groups.json",
1054 "summary": "Get a list of groups"
1055 },
1056 "search_groups":{
1057 "httpMethod":"GET",
1058 "uri": "search.json?query=\"{query} type:group\"",
1059 "summary": "Uses a search query to get a list of groups",
1060 "parameters":{
1061 "query":{
1062 "location": "uri",
1063 "description":"Zendesk Search Query",
1064 "type": "string",
1065 "required": true
1066 }
1067 }
1068 },
1069 "create_group": {
1070 "httpMethod":"POST",
1071 "uri": "groups.json",
1072 "summary": "Create a group",
1073 "parameters":{
1074 "data": {
1075 "type": "array",
1076 "location": "body",
1077 "description":"Group JSON",
1078 "filters": "json_encode",
1079 "required": true
1080 },
1081 "Content-Type":{
1082 "type": "string",
1083 "location":"header",
1084 "static": "application/json"
1085 }
1086 }
1087 },
1088 "delete_group": {
1089 "httpMethod":"DELETE",
1090 "uri": "groups/{id}.json",
1091 "summary": "Delete a group",
1092 "parameters":{
1093 "id":{
1094 "location": "uri",
1095 "description":"Group to delete by ID",
1096 "type": "integer",
1097 "required": true
1098 }
1099 }
1100 },
1101 "get_group": {
1102 "httpMethod":"GET",
1103 "uri": "groups/{id}.json",
1104 "summary": "Get a ticket",
1105 "parameters":{
1106 "id":{
1107 "location": "uri",
1108 "description":"Group to get by ID",
1109 "type": "integer",
1110 "required": true
1111 }
1112 }
1113 },
1114 "update_group": {
1115 "httpMethod":"PUT",
1116 "uri": "groups/{id}.json",
1117 "summary": "Update a group",
1118 "parameters":{
1119 "id": {
1120 "location": "uri",
1121 "description":"Group to update by ID",
1122 "type": "integer",
1123 "required": true
1124 },
1125 "data": {
1126 "type": "array",
1127 "location": "body",
1128 "description":"Group JSON",
1129 "filters": "json_encode",
1130 "required": true
1131 },
1132 "Content-Type":{
1133 "type": "string",
1134 "location":"header",
1135 "static": "application/json"
1136 }
1137 }
1138 }
1139}
1140```
1141
1142### Guzzle\Service\Description\ServiceDescription
1143
1144Commands are now called Operations
1145
1146**Before**
1147
1148```php
1149use Guzzle\Service\Description\ServiceDescription;
1150
1151$sd = new ServiceDescription();
1152$sd->getCommands(); // @returns ApiCommandInterface[]
1153$sd->hasCommand($name);
1154$sd->getCommand($name); // @returns ApiCommandInterface|null
1155$sd->addCommand($command); // @param ApiCommandInterface $command
1156```
1157
1158**After**
1159
1160```php
1161use Guzzle\Service\Description\ServiceDescription;
1162
1163$sd = new ServiceDescription();
1164$sd->getOperations(); // @returns OperationInterface[]
1165$sd->hasOperation($name);
1166$sd->getOperation($name); // @returns OperationInterface|null
1167$sd->addOperation($operation); // @param OperationInterface $operation
1168```
1169
1170### Guzzle\Common\Inflection\Inflector
1171
1172Namespace is now `Guzzle\Inflection\Inflector`
1173
1174### Guzzle\Http\Plugin
1175
1176Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below.
1177
1178### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log
1179
1180Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively.
1181
1182**Before**
1183
1184```php
1185use Guzzle\Common\Log\ClosureLogAdapter;
1186use Guzzle\Http\Plugin\LogPlugin;
1187
1188/** @var \Guzzle\Http\Client */
1189$client;
1190
1191// $verbosity is an integer indicating desired message verbosity level
1192$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE);
1193```
1194
1195**After**
1196
1197```php
1198use Guzzle\Log\ClosureLogAdapter;
1199use Guzzle\Log\MessageFormatter;
1200use Guzzle\Plugin\Log\LogPlugin;
1201
1202/** @var \Guzzle\Http\Client */
1203$client;
1204
1205// $format is a string indicating desired message format -- @see MessageFormatter
1206$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT);
1207```
1208
1209### Guzzle\Http\Plugin\CurlAuthPlugin
1210
1211Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`.
1212
1213### Guzzle\Http\Plugin\ExponentialBackoffPlugin
1214
1215Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes.
1216
1217**Before**
1218
1219```php
1220use Guzzle\Http\Plugin\ExponentialBackoffPlugin;
1221
1222$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge(
1223 ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429)
1224 ));
1225
1226$client->addSubscriber($backoffPlugin);
1227```
1228
1229**After**
1230
1231```php
1232use Guzzle\Plugin\Backoff\BackoffPlugin;
1233use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
1234
1235// Use convenient factory method instead -- see implementation for ideas of what
1236// you can do with chaining backoff strategies
1237$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge(
1238 HttpBackoffStrategy::getDefaultFailureCodes(), array(429)
1239 ));
1240$client->addSubscriber($backoffPlugin);
1241```
1242
1243### Known Issues
1244
1245#### [BUG] Accept-Encoding header behavior changed unintentionally.
1246
1247(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e)
1248
1249In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to
1250properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen.
1251See issue #217 for a workaround, or use a version containing the fix.