Httpful

repository·master·Indexed 23 days ago

https://github.com/nategood/httpful

A simple, readable, and flexible HTTP client library for PHP 8.0+. It features automatic payload serialization, smart response parsing via MIME handlers (including JSON, CSV, and XML), and support for various HTTP methods and authentication types such as Basic, Digest, and NTLM.

Tokens
4.3K
Snippets
6
Records
38
Agent score
82%

What's inside httpful

  1. How Handlers work in Httpful

    master

    Handlers are classes responsible for two main tasks: parsing response bodies and serializing request payloads.

    To create a custom handler, you must extend the \Httpful\Handlers\MimeHandlerAdapter class and implement the following two methods:

    1. serialize($payload): Converts a data structure (like an array) into a serialized format (like a string) to be used as the body of an outgoing request.
    2. parse($body): Takes a raw response body (usually a string) and converts it into a usable data structure (like an array or object).

    Once a handler is registered to a specific MIME type, Httpful will automatically use that handler for any requests or responses matching that type.

    <?php
    
    class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
    {
        public function parse($body)
        {
            return str_getcsv($body);
        }
    
        public function serialize($payload)
        {
            $serialized = '';
            foreach ($payload as $line) {
                $serialized .= '"' . implode('","', $line) . '"' . "\n";
            }
            return $serialized;
        }
    }
    
    Httpful::register('text/csv', new SimpleCsvHandler());
  2. Install Httpful from source

    master
    Since Httpful is PSR-0 compliant, you can install it by cloning the repository and using a PSR-0 compatible autoloader (such as Symfony's ClassLoader). Alternatively, you can use the built-in autoloader by requiring bootstrap.php in your project.
  3. Install Httpful via Composer

    master

    Add nategood/httpful to your composer.json file to install the library using Composer. This is the recommended method for managing dependencies in larger projects.

    {
        "require": {
            "nategood/httpful": "*"
        }
    }
  4. Create and register a custom Handler

    master

    You can extend Httpful's functionality by implementing a custom handler for specific MIME types.

    1. Create a class that extends \Httpful\Handlers\MimeHandlerAdapter.
    2. Implement parse($body) to handle incoming response data.
    3. Implement serialize($payload) to handle outgoing request data.
    4. Register the handler using Httpful::register($mimeType, $handlerInstance).

    Example of a CSV handler:

    <?php
    
    class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
    {
        /**
         * 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)
        {
            $serialized = '';
            foreach ($payload as $line) {
                $serialized .= '"' . implode('","', $line) . '"' . "\n";
            }
            return $serialized;
        }
    }
    
    // Register the handler for the text/csv mime type
    Httpful::register('text/csv', new SimpleCsvHandler());
  5. Build a custom Phar archive

    master

    You can build your own Phar archive using the included build script.

    Requirements:

    • Ensure php.ini has phar.readonly set to Off or 0.
    • Create an empty downloads directory in the project root before running the build.
  6. Implement a custom MimeHandlerAdapter

    master

    To support custom mime-types or override default parsing/serialization behavior in Httpful, you can create a class that extends MimeHandlerAdapter.

    Handlers are responsible for two main tasks:

    1. parse($body): Converts a raw string body into a usable data structure (e.g., an array or object).
    2. serialize($payload): Converts a data structure back into a string format suitable for an HTTP request body.

    When implementing your own handler, you can use the init(array $args) method for setup and the protected stripBom($body) method to clean Byte Order Marks from incoming string bodies.

  7. Make a basic HTTP request with Httpful

    master

    Use the \Httpful\Request class to perform HTTP methods like get(), post(), put(), etc. The library supports automatic JSON parsing and custom headers.

    Note: In version 1.0.0+, SSL certificate validation is enabled by default. If you need to skip strict SSL validation, use the withoutStrictSSL() method.

    // Make a request to the GitHub API with a custom
    // header of "X-Trvial-Header: Just as a demo".
    $url = "https://api.github.com/users/nategood";
    $response = \Httpful\Request::get($url)
        ->expectsJson()
        ->withXTrivialHeader('Just as a demo')
        ->send();
    
    echo "{$response->body->name} joined GitHub on " .
                            date('M jS', strtotime($response->body->created_at)) ."\n";
  8. Configure SSL certificate validation

    master
    As of version 1.0.0, Httpful makes certificate validation the default for security. If you are working in an environment where you must bypass strict SSL validation, you can explicitly call the withoutStrictSSL() method on your request object.
  9. Configure the XmlHandler

    master

    The XmlHandler can be initialized with a configuration array to control how XML is parsed and processed. This is useful for specifying XML namespaces or setting specific libxml options for the underlying PHP simplexml_load_string call.

    Available configuration keys:

    • namespace: (string) The XML namespace to use with simple_load_string.
    • libxml_opts: (int) Libxml constants (see PHP libxml constants) to control parsing behavior.