Last active
January 24, 2023 14:42
-
-
Save sagittaracc/4183cc6b74f178fdff3439bbd12283d0 to your computer and use it in GitHub Desktop.
PHP Flask Python style routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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