2

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

use GuzzleHttp\Event\EmitterInterface;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\CompleteEvent;

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743

2 Answers2

4

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 GuzzleHttp\Client($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.

Radon8472
  • 4,285
  • 1
  • 33
  • 41
0

Here is the example code which is equivalent to onBefore event:

use Psr\Http\Message\RequestInterface;

class SimpleSubscriber {
    public function __invoke(RequestInterface $request, array $options)
    {
        echo 'Before!';
    }
}

Source: 7efe898 commit of systemhaus/GuzzleHttpMock fork of aerisweather/GuzzleHttpMock.

Related: How do I profile Guzzle 6 requests?

kenorb
  • 155,785
  • 88
  • 678
  • 743