How Handlers work in Httpful
masterHandlers 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:
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.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());