1. Go to this page and download the library: Download tnapf/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/ */
tnapf / router example snippets
use Tnapf\Router\Router;
use Tnapf\Router\Routing\Methods;
use Tnapf\Router\Routing\RouteRunner;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
$router = new Router();
$handler = static function (
ServerRequestInterface $request,
ResponseInterface $response,
RouteRunner $route
) {
$response->getBody()->write("Hello World");
return $response;
};
$route = Route::new(uri: "uri", controller: $handler, methods: Methods::GET);
$router->addRoute($route);
$route = Route::new(uri: "uri", controller: static fn() => new TextResponse(), methods: Methods::GET, Methods::POST); // can also spread Methods::ALL
$router->addRoute($route);
class HelloWorld implements ControllerInterface
{
public function handle(
ServerRequestInterface $request,
ResponseInterface $response,
RouteRunner $route
): ResponseInterface {
$response->getBody()->write("Hello World");
return $response;
}
};
$router->get("/home", new HelloWorld());
$response = new HttpSoft\Response\HtmlResponse('<p>HTML</p>');
$response = new HttpSoft\Response\JsonResponse(['key' => 'value']);
$response = new HttpSoft\Response\JsonResponse("{key: 'value'}");
$response = new HttpSoft\Response\TextResponse('Text');
$response = new HttpSoft\Response\XmlResponse('<xmltag>XML</xmltag>');
$response = new HttpSoft\Response\RedirectResponse('https/example.com');
$response = new HttpSoft\Response\EmptyResponse();
use HttpSoft\Response\TextResponse;
use Psr\Http\Message\ResponseInterface;
use Tnapf\Router\Router;
")); // register routes outside the HttpServer closure!!
$http = new React\Http\HttpServer(static function (Psr\Http\Message\ServerRequestInterface $request) use ($router) {
return $router->run($request); // pass the request to the router
});
$socket = new React\Socket\SocketServer('0.0.0.0:8000');
$http->listen($socket);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.