Routes are defined through route handlers, which are functions that trigger whenever a client hits a specific http endpoint.
You can map a route handler using $router->addHandler()
use CatPaw\Web\Interfaces\ServerInterface;
use CatPaw\Web\Interfaces\RouterInterface;
function handler() {
return "there are no cats here";
}
function main(
ServerInterface $server,
RouterInterface $router,
):void {
$router->addHandler("GET", "/cats", handler(...))
->unwrap($error) or die($error);
$server->start()
->unwrap($error) or die($error);
}
This creates a GET /cats route which responds with "there are no cats here".
Note
All paths MUST start with /
.
Similarly to the GET example, $router->addHandler("POST", ...)
will map a POST route
use CatPaw\Web\Interfaces\ServerInterface;
use CatPaw\Web\Interfaces\RouterInterface;
use CatPaw\Web\Body;
function handler(Body $body){
return "Received body: {$body->text()}\n";
}
function main(
ServerInterface $server,
RouterInterface $router,
):void {
$router->addHandler("POST", "/cats", handler(...))
->unwrap($error) or die($error);
$server->start()
->unwrap($error) or die($error);
}
You can automate routes definitions by describing them through the filesystem.
Create a new src/api directory
mkdir -p src/api
Scan the directory using $server->withApiLocation()
function main(ServerInterface $server):void {
$server
->withApiLocation("src/api")
->withApiPrefix("/api/v1")
->start()
->unwrap($error) or die($error);
}
You can now define your routes within the src/api
directory.
There are some rules you will need to follow.
- Each file must take the name
{method}.php
, where{method}
is the http method your file accepts.File Name Final Web Path src/api/get.php GET /api/v1 src/api/about/get.php GET /api/v1/about src/api/about/ {username}
/get.phpGET /api/v1/about/ {username}
src/api/about/ {username}
/post.phpPOST /api/v1/about/ {username}
... ... - Each file must return a function.
// src/api/get.php use function CatPaw\Core\success; return static function(){ return success("hello world"); };
Note
{username}
is a path parameter, read more here.