Guzzle 6 中 GuzzleHttp\Event\SubscriberInterface 的等价物是什么?

What's the equivalent of GuzzleHttp\Event\SubscriberInterface in Guzzle 6?

在 Guzzle 5.3 中,您可以使用 event subscribers,如下例所示:

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!';
    }
}

Guzzle 6 中的等效示例是什么?

因为我已经 phpunit 测试使用 onBefore/onCompleteonError 事件订阅者并且文件需要升级。

这是等同于 onBefore 事件的示例代码:

use Psr\Http\Message\RequestInterface;

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

来源:7efe898 commit of systemhaus/GuzzleHttpMock fork of aerisweather/GuzzleHttpMock.

相关:

在 Guzzle 6 中,您必须添加这样的事件 class/函数:

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

$client = new GuzzleHttp\Client($options);

你 class 应该是这样的:

class SimpleSubscriber
{

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

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

您可以在 Guzzle 的 UPGRADING.md 中阅读此内容。

阅读 guzzly options 以了解您可以使用 $options 做什么。