I've written a small routing system in PHP but I'm not sure if it's done the right way and what changes can they be done to the code and improvements.
<?php
namespace Twelve\Router;
use Twelve\Utils\Utils;
class Router
{
public
$routeMaps = [],
$controller;
private $_route = [];
public function add($name, $pattern, $controller, array $params = [])
{
if(!isset($this->routeMaps[$name]))
$this->routeMaps[$name] =
[
'pattern' => $pattern,
'controller' => $controller,
'params' => $params,
];
}
public function findMatch($url)
{
foreach($this->routeMaps as $routeMap)
{
$this->regex = $this->buildRegex($routeMap['pattern'], $routeMap['params']);
// Let's test the route.
if(preg_match($this->regex, $url))
{
return (array) $routeMap['controller'];
}
}
}
public function buildRegex($uri, array $params)
{
// FInd {params} in URI
if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $this->matches, PREG_SET_ORDER))
{
foreach($this->matches as $isMatch)
{
// Swap {param} with a placeholder
$this->uri = str_replace($isMatch, "%s", $uri);
}
// Build final Regex
$this->finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
$this->finalRegex = vsprintf($this->finalRegex, $params);
return $this->finalRegex;
}
}
public function dispatch(array $route = [], $url)
{
$this->setController($route['0']);
$this->setAction($this->getController());
$this->setParams(explode('/', $url));
$this->controller = $this->getController();
array_pop($this->controller);
$this->controller = implode('\\', $this->controller);
call_user_func_array([new $this->controller, $this->action], $this->params);
}
public function setController($controller)
{
$this->controller = explode(':', $controller);
}
public function getController()
{
return $this->controller;
}
public function setAction($action)
{
$this->action = end($action);
}
public function getAction()
{
return $this->action;
}
public function setParams($params)
{
$this->params = array_slice($params, 4);
}
public function getParams()
{
return $this->params;
}
public function run($uri, array $route = null)
{
$route = $this->findMatch($uri);
Utils::var_dump($route);
$this->dispatch($route, $uri);
}
}