Skip to content
Advertisement

What’s the equivalent of GuzzleHttpEventSubscriberInterface in Guzzle 6?

In Guzzle 5.3 you can use event subscribers as in the following example:

use GuzzleHttpEventEmitterInterface;
use GuzzleHttpEventSubscriberInterface;
use GuzzleHttpEventBeforeEvent;
use GuzzleHttpEventCompleteEvent;

class SimpleSubscriber implements SubscriberInterface
{
    public function getEvents()
    {
        return [
            // Provide name and optional priority
            'before'   => ['onBefore', 100],
            'complete' => ['onComplete'],
            // You can pass a list of listeners with different priorities
            'error'    => [['beforeError', 'first'], ['afterError', 'last']]
        ];
    }

    public function onBefore(BeforeEvent $event, $name)
    {
        echo 'Before!';
    }

    public function onComplete(CompleteEvent $event, $name)
    {
        echo 'Complete!';
    }
}

What would be the equivalent example in Guzzle 6?

As I’ve phpunit tests which are using onBefore/onComplete and onError event subscribers and the files needs to be upgraded.

Advertisement

Answer

In Guzzle 6 you must add your event class / functions like this:

$handler = HandlerStack::create();
$handler->push(Middleware::mapRequest(array('SimpleSubscriber','onBefore');
$handler->push(Middleware::mapResponse(array('SimpleSubscriber','onComplete');

$client = new GuzzleHttpClient($options);

and you class should look like this:

class SimpleSubscriber
{

    public function onBefore(RequestInterface $request)
    {
        echo 'Before!';
        return $request;
    }

    public function onComplete(ResponseInterface $response)
    {
        echo 'Complete!';
        return $response;
    }
}

You can read this in UPGRADING.md from Guzzle.

Read guzzly options to understand what you can do with $options.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement