Building Web Service Clients with Guzzle (Symfony Live Session Notes)
Wayne Eaker
The Symfony Live conference is happening concurrently with DrupalCon Portland. Since Symfony libraries (such as Guzzle) are in Drupal 8 core, I'm attending some Symfony sessions to learn how to use some of the libraries.
PHP HTTP Clients
- HTTP Stream Wrapper (file_get_contents()): Easy to use for GET requests, built into PHP. No support for parallel requests or persistent connections. Data must be loaded into memory. Have to work with stream contexts to do anything complicated.
- cURL: Fast, supports streaming requests and responses. Cumbersome API.
- PECL HTTP: Custom extension.
- Sockets (fsockopen): More control, but lots of effort.
Guzzle Library
Link: http://guzzlephp.org
By: Michael Dowling, the speaker giving the talk.
Features
* Extensible
* Easy to use
* Built on cURL
Installing
- Install with Composer
- Also available as stripped down packages.
Guzzle and Drupal
- Replaced drupal_http_request()
- Drupal 8 process helped make Guzzle better. (added async plugin)
Clients
- Creates and sends requests.
- Can specify base URLs.
- $response = $client->get($url)->send();
- echo $response->getBody();
- $response->json();
- If response is over 2MB, it starts storing on disk to save memory
- $response->getStatusCode(), other header methods.
- Streaming: You can stream the contents of one request as a POST to another URL
- Error Handling: Application / Protocol errors are Exceptions
- Parallel Requests
Symfony Event Dispatcher
- Glue of Guzzle.
- Hook into events as subscriber and listener
Web Server Clients
- Most wrap cURL
- Create functions for each API operation
- Error handling, extensibility?
Guzzle\Service\Client
- Command: encapsulates actions of an API. Request serialization, Response parsing
- Operation Commands: Powered by a Service Description
- Service Description: JSON document. Defines inputs and outputs. Versionable and swappable.
Client Factory
- Encapsulates bootstrapping of client.
- Input Validation
- Used with a ServiceBuilder