The Handler stack

Last updated on
22 February 2019

"Guzzle clients use a handler and middleware system to send HTTP requests."

You can find the full documentation about the handler stack here: http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html

Let's imagine you have the need to add an HTTP Header to all of your Requests sent to a REST Service.

An option could be to update all of your Guzzle Service Description by adding the header parameter within each command... .... ... omg no please don't do it :( Guzzle guys already knew about you and your needs and were too sad imagining you while doing something like that.

"That's why" an handler stack has been introduced as part of the Client configurations.

HTTP Client Manager allows you to use this "service" by emitting a specific event called http_client.handler_stack
So, all you have to do is just to create or update an existing EventSubscriber and subscribe to this particular event.

Here it is an example from the HTTP Client Manager - Example module:

<?php

namespace Drupal\http_client_manager_example\EventSubscriber;

use Drupal\http_client_manager\Event\HttpClientEvents;
use Drupal\http_client_manager\Event\HttpClientHandlerStackEvent;
use GuzzleHttp\Middleware;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class HttpClientManagerExampleSubscriber.
 */
class HttpClientManagerExampleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    return [
      HttpClientEvents::HANDLER_STACK => ['onHandlerStack'],
    ];
  }

  /**
   * This method is called whenever the http_client.handler_stack event is
   * dispatched.
   *
   * @param \Drupal\http_client_manager\Event\HttpClientHandlerStackEvent $event
   *   The HTTP Client Handler stack event.
   */
  public function onHandlerStack(HttpClientHandlerStackEvent $event) {
    if ($event->getHttpServiceApi() != 'example_services') {
      return;
    }

    $handler = $event->getHandlerStack();
    $middleware = Middleware::mapRequest([$this, 'addExampleServiceHttpHeader']);
    $handler->push($middleware, 'example_services');
  }

  /**
   * Add example service HTTP Header.
   *
   * @param \Psr\Http\Message\RequestInterface $request
   *   The current Request object.
   *
   * @return MessageInterface
   *   Return an instance with the provided value for the specified header.
   */
  public function addExampleServiceHttpHeader(RequestInterface $request) {
    return $request->withHeader('X-EXAMPLE-HTTP-HEADER', 'example_services');
  }

}

There you go :)

Have fun!

Help improve this page

Page status: No known problems

You can: