Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Last active January 24, 2023 14:42
Show Gist options
  • Save sagittaracc/4183cc6b74f178fdff3439bbd12283d0 to your computer and use it in GitHub Desktop.
Save sagittaracc/4183cc6b74f178fdff3439bbd12283d0 to your computer and use it in GitHub Desktop.
PHP Flask Python style routes
<?php
#[Attribute]
class Route
{
function __construct(
public string $endpoint,
public string $verb = 'GET'
) {}
}
class AppController
{
#[Route("/hello/(\w+)")]
public function index($name)
{
echo $name;
}
#[Route("/user/edit/(\d+)")]
public function edit($id)
{
return true;
}
#[Route('/site/main/(\d+)/(\w+)')]
public function doSomeWork($id, $name)
{
echo "I am working with an element by id $id and its name is $name";
}
}
$routes = [];
$myendpoint = "/hello/yuriy";
$controller = new ReflectionClass(AppController::class);
$actions = $controller->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($actions as $action) {
$attributes = $action->getAttributes();
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
if (!($route instanceof Route)) {
continue;
}
$verb = $route->verb;
$endpoint = $route->endpoint;
$routes[$verb][$endpoint] = $action;
}
}
$found = false;
foreach ($routes['GET'] as $route => $callback) {
if (preg_match("`$route`", $myendpoint, $matches)) {
array_shift($matches);
call_user_func_array(array(new $callback->class, $callback->name), $matches);
$found = true;
break;
}
}
if (!$found) {
throw new Exception('404');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment