Guzzle 6中的GuzzleHttp \ Event \ SubscriberInterface相当于什么?

时间:2017-09-22 19:20:35

标签: php guzzle guzzle6 guzzlehttp

在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 / onBeforeonComplete事件订阅者进行onError测试,并且需要升级文件。

2 个答案:

答案 0 :(得分:3)

在Guzzle 6中,您必须添加事件类/函数,如下所示:

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

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

您的班级应该看起来像这样:

class SimpleSubscriber
{

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

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

您可以在UPGRADING.md中从Guzzle上阅读。

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

答案 1 :(得分:0)

以下示例代码等同于onBefore事件:

use Psr\Http\Message\RequestInterface;

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

来源:7efe898 commitsystemhaus/GuzzleHttpMock分叉aerisweather/GuzzleHttpMock

相关:How do I profile Guzzle 6 requests?