【问题标题】:What's the equivalent of GuzzleHttp\Event\SubscriberInterface in Guzzle 6?Guzzle 6 中的 GuzzleHttp\Event\SubscriberInterface 等价物是什么?
【发布时间】:2020-04-09 17:09:56
【问题描述】:

在 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 中的等效示例是什么?

正如我使用onBefore/onCompleteonError 事件订阅者的phpunit 测试,文件需要升级。

【问题讨论】:

    标签: php guzzle6 guzzle


    【解决方案1】:

    在 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;
        }
    }
    

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

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

    【讨论】:

    • 你忘记了 options 变量的声明,应该设置如下:$options = ['handler' => $handler];
    • 我现在在选项文档中添加了一个链接。
    【解决方案2】:

    这是相当于onBefore事件的示例代码:

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

    来源:systemhaus/GuzzleHttpMocksystemhaus/GuzzleHttpMockaerisweather/GuzzleHttpMock 的分支。

    相关:How do I profile Guzzle 6 requests?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      • 2014-05-08
      • 2014-06-12
      • 1970-01-01
      • 2022-11-28
      • 2021-06-19
      相关资源
      最近更新 更多