voku/httpful

A Readable, Chainable, REST friendly, PHP HTTP Client

v0.7.1 2019-04-30 22:36 UTC

README

Build Status Coverage Status Codacy Badge Latest Stable Version Total Downloads License Donate to this project using Paypal Donate to this project using Patreon

📯 Httpful

Features

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS)
  • Custom Headers
  • Automatic "Smart" Parsing
  • Automatic Payload Serialization
  • Basic Auth
  • Client Side Certificate Auth
  • Request "Templates"
  • PSR-3: Logger Interface
  • PSR-7: HTTP Message Interface
  • PSR-18: HTTP Client Interface

Examples

<?php

// Make a request to the GitHub API.
$uri = 'https://api.github.com/users/voku';
$response = \Httpful\Client::get($uri, \Httpful\Mime::JSON);

echo $response->getBody()->name . ' joined GitHub on ' . date('M jS Y', strtotime($response->getBody()->created_at)) . "\n";
<?php

// Make a request to the GitHub API with a custom
// header of "X-Foo-Header: Just as a demo".
$uri = 'https://api.github.com/users/voku';
$response = \Httpful\Client::get_request($uri)->addHeader('X-Foo-Header', 'Just as a demo')
                                              ->expectsJson()
                                              ->send();

echo $response->getBody()->name . ' joined GitHub on ' . date('M jS Y', strtotime($response->getBody()->created_at)) . "\n";

Installation

composer require voku/httpful

Handlers

Handlers are simple classes that are used to parse response bodies and serialize request payloads. All Handlers must extend the MimeHandlerAdapter class and implement two methods: serialize($payload) and parse($response). Let's build a very basic Handler to register for the text/csv mime type.

<?php

class SimpleCsvHandler implements \Httpful\Handlers\MimeHandlerInterface
{
    /**
     * Takes a response body, and turns it into 
     * a two dimensional array.
     *
     * @param string $body
     * @return mixed
     */
    public function parse($body)
    {
        return str_getcsv($body);
    }

    /**
     * Takes a two dimensional array and turns it
     * into a serialized string to include as the 
     * body of a request
     *
     * @param mixed $payload
     * @return string
     */
    public function serialize($payload)
    {
        // init
        $serialized = '';
        
        foreach ($payload as $line) {
            $serialized .= '"' . implode('","', $line) . '"' . "\n";
        }
        
        return $serialized;
    }
}

Finally, you must register this handler for a particular mime type.

HttpSetup::register(Mime::CSV, new SimpleCsvHandler());

After this registering the handler in your source code, by default, any responses with a mime type of text/csv should be parsed by this handler.