PHP code example of woss / http

1. Go to this page and download the library: Download woss/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/ */

    

woss / http example snippets


use Woss\Http\Message\{Request, Response};

function (Request $request, $next): Response
{
    log('debug', (string) $request);
    
    $response = $next($request);
    
    log('debug', (string) $response);
    
    return $response;
}

use Woss\Http\Message\{Request, Response, Stream};

class ListAllUsers
{
    public function __construct($users)
    {
        $this->users = $users;
    }
    
    public function handle(Request $request): Response
    {
        $users = $this->users->getAll();
        $content = json_encode($users);
        
        $body = new Stream('php://memory', 'w');
        
        $body->write($content);
        
        $response = new Response($body, 200, [
            'Content-Type' => 'application/json',
            'Content-Length' => strlen($content),
        ]);
        
        return $response;
    }
}

use Woss\Http\Message\{Request, Response};

class Cache
{
    public function __construct($cache)
    {
        $this->cache = $cache;
    }
    
    public function process(Request $request, $next): Response
    {
        // Se houver cache da resposta, retorne-a
        if ($this->cache->exists($request)) {
            return $this->cache->get($request);
        }
        
        // Caso contrário, gere a resposta HTTP e a armazene no cache
        $response = $next($request);
        
        $this->cache->create($request, $response);
        
        return $response;
    }
}

use Woss\Http\Message\{ServerRequest, Request, Response};
use Woss\Http\Server\Pipeline;

$pipe = new Pipeline([
    function (Request $request, $next): Response
    {
        log('debug', (string) $request);
        
        $response = $next($request);
        
        log('debug', (string) $response);
        
        return $response;
    },
    new Cache($services->get('cache')),
    new ListAllUsers($services->get('users'))
]);

$request = ServerRequest::fromGlobals();
$response = $pipe->handle($request);

echo (string) $response;