1. Go to this page and download the library: Download commandstring/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/ */
commandstring / router example snippets
$socket = new \React\Socket\SocketServer("127.0.0.1:8000");
$router = new \Router\Http\Router($socket, true);
$router->listen();
use Router\Http\Methods;
$router->match([Methods::GET], "/", function() { /* ... */ });
$router->get("/home", function ($req, $res) {
$res->getBody()->write("Welcome home!");
return $res;
});
class Home {
public static function handler($req, $res) {
$res->getBody()->write("Welcome home!");
return $res;
}
}
$router->get("/home", [Home::class, "handler"]);
$router->map404("/(.*)", function ($req, $res) {
$res->getBody()->write("{$req->getRequestTarget()} is not a valid route");
return $res;
});
$router->map500("/(.*)", function ($req, $res) {
$res->getBody()->write("An error has happened internally :(");
return $res;
});
$router->beforeMiddleware("/admin?(.*)", function (ServerRequest $req, Closure $next) {
if (!isAdmin()) {
return new RedirectResponse("/", 403);
}
return $next(new Response);
});
$router->all("/admin/roster/json", function (ServerRequest $req, Response $res, Closure $next) {
/*
some code that gets the admin roster and converts to json
*/
$res->getBody()->write($jsonString);
$res->withHeader("content-type", "application/json");
return $next($res);
});
$router->afterMiddleware("/admin?(.*)", function (ServerRequest $req, ResponseInterface $res) {
/*
some code that makes sure the body is a valid json string
*/
if (!jsonValid((string)$res->getBody())) {
return new EmptyResponse(500);
}
return $res;
});
use CommandString\Env\Env;
$env = new Env;
$env->twig = new Environment(new \Twig\Loader\FilesystemLoader("/path/to/views"));
// ...
$router->get("/home", function ($req, $res) {
return new HtmlResponse($env->get("twig")->render("home.html"));\\\
});
$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();