在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
和onComplete
事件订阅者进行onError
测试,并且需要升级文件。
答案 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
commit的systemhaus/GuzzleHttpMock
分叉aerisweather/GuzzleHttpMock
。