Public fundtion in router class:
public function match($url){
// Match to the fixed URL format /controller/action
$reg_exp = "/^(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)$/";
if (preg_match($reg_exp, $url, $matches)) {
// Get named capture group values
$params = [];
foreach ($matches as $key => $match) {
if (is_string($key)) {
$params[$key] = $match;
}
}
$this->params = $params;
return true;
}
return false;
}
public function getParams(){
return $this->params;
}
when this is called in index.php:
// Match the requested route
$url = $_SERVER['REQUEST_URI'];
echo "Requested URI: ". $url ."<br />";
if ($router->match($url)) {
echo '<pre>';
var_dump($router->getParams());
echo '</pre>';
} else {
echo "No route found for URL '$url'";
}
It doesn’t return an associative array. Ideally, I was anticipating this behavior →Local host analogue
On live server it doesn’t works.
seems like this is not getting true:
$router->match($url)
Advertisement
Answer
The url is /mvc/public/ which is begin and end with a slash, so the regex doesn’t match.
Fixed with:
"/^/(?P<controller>[a-z-]+)/(?P<action>[a-z-]+)/$/"