代码之家  ›  专栏  ›  技术社区  ›  kenorb

Guzzle 6中的GuzzleHttp\Event\SubscriberInterface等效于什么?

  •  2
  • kenorb  · 技术社区  · 7 年前

    在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

    2 回复  |  直到 7 年前
        1
  •  4
  •   Radon8472    4 年前

    在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

    阅读 guzzly options $options .

        2
  •  0
  •   kenorb    7 年前

    下面是示例代码,相当于 onBefore 事件:

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

    资料来源: 7efe898 commit systemhaus/GuzzleHttpMock 叉子 aerisweather/GuzzleHttpMock .

    相关: How do I profile Guzzle 6 requests?