I try to build a routing system with PHP. I have a problem with changeable URLs.
private $routes = array(
"blog" => array("Blog", "GetAll"),
"/blog\/*/" => array("Blog", "GetOne"),
);
private $query;
public function __construct()
{
$this->query = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_URL);
}
public function SendAction()
{
$route = array();
if (array_key_exists($this->query, $this->routes)) {
$route['controller'] = $this->routes[$this->query][0];
$route['action'] = $this->routes[$this->query][1];
$route['params'] = $this->routes[$this->query][2];
} else {
$route['controller'] = "Error";
$route['action'] = "Main";
$route['params'] = array();
}
return $route;
}
The problem is with the url that contains abc/my_custom_variable_or/slug
.
I need to get my_custom_variable_or
and slug
and put them into params['fdsaf']
so I can use it in my controller
I find a temp solution with else if, like: else if (preg_match("/blog\/*/", $this->query))
.... explode()
etc...
To make my system more flexible, I need to make something in $routes
array. The routes array will be a different file.
===Sample inputs and the expected results===
URL: blog
$route['controller'] = Blog
$route['action'] = GetAll
$route['params'] = array()
URL: blog/my-first-post
$route['controller'] = Blog
$route['action'] = GetOne
$route['params'] = array('slug' => 'my-first-post')
URL: blog/user/martin/page2 (page2 is optional)
$route['controller'] = Blog
$route['action'] = GetUserPost
$route['params'] = array('slug' => 'martin')