I've been working on implementing a simple PHP router and have managed to make it work with required parameters. However, I'm struggling to implement optional parameters but I failed. I'll provide the relevant code for clarity.
Firstly, this is my index.php:
<?php
$app->route->get("/user/:id/?post_id", [SiteController::class, "contact"]);
?>
In the above code, I've used a colon (:id) for required parameters and a question mark (?post_id) for optional parameters.
Secondly, here is my Router class:
class Router {
public function resolve() {
$method = $this->request->getMethod();
$url = $this->request->getUrl();
foreach ($this->router[$method] as $routeUrl => $target) {
$pattern = preg_replace('/\/:([^\/]+)/', '/(?P<$1>[^/]+)', $routeUrl);
if (preg_match('#^' . $pattern . '$#', $url, $matches)) {
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
call_user_func([new $target[0], $target[1]], ...array_values($params));
exit();
}
}
throw new \Exception();
}
}
I need assistance in solving the mystery of implementing optional parameters. Any help would be greatly appreciated. Thank you!