Http
, (*1)
HTTP library compliant with proposed PSR-7 message implementation, basically inspired by phly/http, (*2)
Installation
Via composer:, (*3)
{
"require": {
"kemist/http": "1.0.*"
}
}
HTTP Client
This package contains a cURL- and a socket-based HTTP client class.
Basic GET example:, (*4)
<?php
$request=new Kemist\Http\Request('http://httpbin.org/get?sd=43','GET',array('accept'=>'text/html','connection'=>'close'));
// cURL client
$client=new Kemist\Http\Client\CurlClient();
// OR Socket-based client
$client=new Kemist\Http\Client\SocketClient();
$response=$client->send($request);
var_dump($response->getHeaders());
var_dump($response->getBody()->getContents());
Basic POST example:, (*5)
<?php
$request=(new Kemist\Http\Request())
->withUri(new Kemist\Http\Uri('http://httpbin.org/post'))
->withMethod('POST')
->withHeader('accept','text/html')
->withHeader('connection','close')
->withBody(new Kemist\Http\Stream\StringStream('param1=value1¶m2=value2'))
;
// cURL client
$client=new Kemist\Http\Client\CurlClient();
// OR Socket-based client
$client=new Kemist\Http\Client\SocketClient();
$response=$client->send($request);
var_dump($response->getHeaders());
var_dump(json_decode($response->getBody()));
Both client types have the following options:, (*6)
<?php
// Client options and their default values
$options=array(
'follow_redirections' => true,
'max_redirections' => 10,
'use_cookies' => true,
'dechunk_content' => true,
'decode_content' => true,
'connection_timeout' => 30,
'timeout' => 60,
);
// Options are set through the client constructor
$client=new Kemist\Http\Client\SocketClient($options);
HTTP Server
When using the HTTP server component, you can handle incoming request to the server through middleware objects or closures., (*7)
<?php
$server = new Kemist\Http\Server\Server();
// Appends a closure middleware
$server->appendMiddleware(function($request, $response, $server) {
$response->getBody()->write('world!');
return $response;
});
// Prepends a closure middleware
$server->prependMiddleware(function($request, $response, $server) {
$response->getBody()->write('Hello ');
return $response;
});
$response=$server->handle();
echo $response;
You can break the middleware chain by stopping propagation to the next middleware:, (*8)
<?php
$server->appendMiddleware(function($request, $response, $server) {
$response->getBody()->write('This string never appears!');
return $response;
});
$server->prependMiddleware(function($request, $response, $server) {
$response->getBody()->write('Hello world!');
$server->stopPropagation();
return $response;
});
You can also use middlewares extending AbstractMiddleware class. This package ships with one example middleware: IsNotModifiedMiddleware.
It decides if content is not modified comparing some special request and response headers (ETag and Last-Modified) then sets the proper response status code and stops propagation., (*9)
<?php
$server->appendMiddleware(new Kemist\Http\Server\IsNotModifiedMiddleware());