PHP code example of krak / http

1. Go to this page and download the library: Download krak/http library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

krak / http example snippets




interface ResponseFactory {
    public function createResponse($status = 200, array $headers = [], $body = null);
}



use Krak\Http\ResponseFactory;

$rf = new ResponseFactory\DiactorosResponseFactory();
$rf = new ResponseFactory\GuzzleResponseFactory();

// adds html content-type header
$html_rf = new ResponseFactory\HtmlResponseFactory($rf);
// json encodes the body and add json content-type header. Accepts json_encode_options as second parameter
$json_rf = new ResponseFactory\JsonResponseFactory($rf, JSON_PRETTY_PRINT);
// adds text content-type header
$text_rf = new ResponseFactory\TextResponseFactory($rf);

$json_rf->createResponse(200, [], [1,2,3]);



use Krak\Http\Route;

$routes = new Route\RouteGroup();
$routes->get('/', function() {})->with('attribute', 'value');
$routes->group('/foo', function($foo) {
    $sub->get('', 'handler');
    $sub->group('/bar', function($bar) {
        $bar->get('/baz', 'handler');
    });
});
$routes->with('attribute1', 'value');



use Krak\Http\Route;

$routes = new Route\RouteGroup();
// add routes to $routes

$compiler = new Route\RecursiveRouteCompiler();
// compile on a path
$routes = $compiler->compileRoutes($routes, '/');



use Krak\Http\Dispatcher;
$dispatch_factory = new Dispatcher\FastRoute\FastRouteDispatcherFactory();
$dispatch = $dispatch_factory->createDispatcher($routes);
$res = $dispatch->dispatch($req);

// $res->status_code
// $res->matched_route->route
// $res->matched_route->params
// $res->allowed_methods /* if status code is a 405 response */



interface Server {
    /** @param $handler resolves the request into a response object */
    public function serve($handler);
}



$server = new Krak\Http\Server\DiactorosServer();
$server->serve(function($req) {
    return new Zend\Diactoros\Response();
});



use Psr\Http\Message\ServerRequestInterface;
use Krak\Http\Middleware\HttpLink;

function myMiddleware() {
    return function(ServerRequestInterface $req, HttpLink $next) {
        if (certainCondition($req)) {
            return $next($req->withAttribute('a', '1'))->withStatusCode(404);
        }

        return $next->response(404, ['X-Header' => 'value'], 'Some body'); // can also use a php or psr-7 stream.
    };
}



$mw = Krak\Http\Middleware\wrap(function($req, $resp, callable $next) {

});



use function Krak\Http\Middleware\{mount, serveStatic};

$mw = mount('/assets', serveStatic(__DIR__ . '/path/to/assets'));