I'm facing a situation where I don't know how to implement a function, I'm not sure what could be the best and faster solution.
I have a simple Routing object, pretty basic, I don't need advanced functionalities for this particular project... it stores an array of routes, the only methods allowed are GET and POST and this is roughly the class structure:
class Router
{
// Array of Route Objects
private static $binded_routes = array();
// Method used to register a GET route.
public static function get() {}
// Method used to register a POST route.
public static function post() {}
// Other methods here like redirect(), routeTo(), dispatch()
}
Routes can be declared as this:
Router::get('index', 'IndexController@method');
Router::get('users/{id}', 'UserController@showUser');
Router::get('route/to/something', 'Controller@method');
Router::get('route/to/something/{param1}', 'Controller@method1');
Router::get('route/to/something/{param1}/{param2}', 'Controller@method2');
The policy to store GET routes is this:
- Only register route without params (in this example: index, users, route/to/something)
- Where params are specified store them as an array
- Do not store more than one GET route with the same amount of params (in this example declaring 'users/{test}' will throw an error)
Route object is like this:
class Route
{
private $route_type = 'GET';
private $route_name = null;
private $route_uri = null;
private $route_params = array();
private $route_controller = null;
private $route_method = null;
// Functions to correctly store and retrieve the above values
}
So now I'm having trouble on matching GET requests, based on the policy I could do something like that:
- loop through all the binded routes. find an exact match and stop if found.
-> So if a user go to 'route/to/something' I can match the third route and pass execution to the right controller. - If not found, match as much of the route as possible and take the rest as parameters.
-> So if a user go to 'route/to/something/1/2' I can match 'route/to/something' and have array(1,2) as parameters - Now I can simply count the number of params and compare to the routes to find the only one that has the same amount of params.
At the moment I can't think of a way to manage this process without having more than one foreach loop. What could be the best approach for this? is there a way to structure a regexp? and how to generate it?
Any help would be highly appreciated, and if you need some more info just let me know.