binsoul/net-http-response

Specialized response and body classes plus response emitter

dev-master / 1.0.x-dev 2016-04-27 19:57 UTC

This package is auto-updated.

Last update: 2024-10-14 22:37:45 UTC


README

Latest Version on Packagist Software License Total Downloads

Install

Via composer:

$ composer require binsoul/net-http-response

This package provides PSR-7 ResponseInterface compatible response classes specialized for known HTTP status codes and body implementations which extend the PSR-7 StreamInterface with some useful methods. The included response emitter can output responses to different target environments.

Usage

Output a text response on a web server:

<?php

use BinSoul\Net\Http\Response\Body\Type\TextBody;
use BinSoul\Net\Http\Response\Emitter\DefaultEmitter;
use BinSoul\Net\Http\Response\Emitter\Target\SapiTarget;
use BinSoul\Net\Http\Response\Type\Success\OkResponse;

require 'vendor/autoload.php';

$response = new OkResponse(new TextBody('Hello world!'));
$emitter = new DefaultEmitter();
$emitter->emit($response, new SapiTarget());

Capture and display response headers and body:

<?php

use BinSoul\Net\Http\Response\Body\Type\TextBody;
use BinSoul\Net\Http\Response\Emitter\DefaultEmitter;
use BinSoul\Net\Http\Response\Emitter\Target\CaptureTarget;
use BinSoul\Net\Http\Response\Type\Success\OkResponse;

require 'vendor/autoload.php';

// make var_export HTML friendly
function dump($value)
{
    return htmlentities(preg_replace("/\s+=>\s+/m", ' => ', var_export($value, true)));
}

$response = new OkResponse(new TextBody('Hello world!'));
$target = new CaptureTarget();
$emitter = new DefaultEmitter();
$emitter->emit($response, $target);

?>
<!DOCTYPE html>
<html>
<body>
    <h1>Headers</h1>
    <pre><?= dump($target->getHeaders()) ?></pre>
    <h1>Body</h1>
    <pre><?= dump($target->getBody()) ?></pre>
</body>
</html>

Testing

$ composer test

License

The MIT License (MIT). Please see License File for more information.