PHP code example of ahmard / reaponse

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

    

ahmard / reaponse example snippets


namespace Test;

use Reaponse\Http\HandlerInterface;
use Reaponse\Http\ResponseInterface;

class CountHandler implements HandlerInterface
{
    protected static int $counts = 0;

    public function handle(ResponseInterface $response): void
    {
        self::$counts++;
        $response->write('Count: ' . self::$counts);
        $response->handler()->next();
    }
}

namespace Test;

use Reaponse\Http\HandlerInterface;
use Reaponse\Http\ResponseInterface;

class ServerHandler implements HandlerInterface
{
    public function handle(ResponseInterface $response): void
    {
        $response->html(', Time: ' . date('H:i:s'));
        $response->end('.');
    }
}

use React\EventLoop\Factory;
use React\Socket\Server;
use Reaponse\Http\Middleware;
use Test\CounterHandler;
use Test\ServerHandler;

= new \React\Http\Server($loop, new Middleware($myCounter, $myServer));
$socketServer = new Server($uri, $loop);

$httpServer->listen($socketServer);
$httpServer->on('error', function (Throwable $throwable){
    echo $throwable;
});

echo "Server started at http://{$uri}\n";
$loop->run();

use Reaponse\Http\HandlerInterface;
use Reaponse\Http\ResponseInterface;


class TestHandler implements HandlerInterface
{
    public function handle(ResponseInterface $response): void
    {
        //psr-7 compliant object
        $request = $response->request();
        
        $response->html("Method: {$request->getMethod()}<br/>");
        
        $response->end('Bye!');
    }
}

use Reaponse\Http\HandlerInterface;
use Reaponse\Http\Response;
use Reaponse\Http\ResponseInterface;


class TestHandler implements HandlerInterface
{
    public function handle(ResponseInterface $response): void
    {
        //listens to write event
        $response->on(Response::ON_WRITE, function (){
            echo "Writing...\n";
        });
        //Listens to headers event
        $response->on(Response::ON_HEADERS, function (){
            echo "Headers...\n";
        });
        //Listens to next handler event
        $response->on(Response::ON_NEXT_HANDLER, function (){
            echo "Next handler...\n";
        });
        //Listens to response sending event
        $response->on(Response::ON_BEFORE_SEND, function (){
            echo "Sending...\n";
        });
        
        $response->end('Hello World');
    }
}
bash
php server.php