PHP code example of thruster / http-router

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

    

thruster / http-router example snippets




use Psr\Http\Message\RequestInterface;
use Thruster\Component\HttpRouter\Router;
use Thruster\Component\HttpRouter\RouteProvider;

$application = new class implements RouteProvider {
    public function getRoutes() : array
    {
        return [
            'hello_world' => ['GET', '/', 'hello'],
            ['POST', '/', [$this, 'foo']]
        ];
    }

    public function hello(ServerRequestInterface $request)
    {
        // return new Response(200, [], 'Hello world');
    }

    public function foo(ServerRequestInterface $request)
    {
        // return new Response(404, [], 'Foo Bar');
    }
};


$router = new Router($application);
$response = $router->handleRequest(ServerRequest::fromGlobals()); // PSR-7 Response



use Psr\Http\Message\RequestInterface;
use Thruster\Component\HttpRouter\Router;
use Thruster\Component\HttpRouter\RouteProvider;
use Thruster\Component\HttpRouter\RouteHandler;

$application = new class implements RouteProvider, RouteHandler {
    public function getRoutes() : array
    {
        return [
            'hello_world' => ['GET', '/', 'hello'],
            ['POST', '/', [$this, 'foo']]
        ];
    }

    public function handleRoute(
    	ServerRequestInterface $request,
    	ResponseInterface $response,
    	callable $actionHandler
    ) : ResponseInterface {
    	// ... call actionHandler and return ResponseInterface
    }

    public function handleRouteMethodNotAllowed(
    	ServerRequestInterface $request,
    	ResponseInterface $response,
    	array $allowedMethods
    ) : ResponseInterface {
    	// ... handle method not allowed error
    }

    public function handleRouteNotFound(
    	ServerRequestInterface $request,
    	ResponseInterface $response
    ) : ResponseInterface {
    	// ... handle route not found (404)
    }
};


$router = new Router($application, $application);
$response = $router(ServerRequest::fromGlobals(), new Response()); // PSR-7 Response