Reputation: 3046
I have a router class in my php project that works like this:
public function dispatch(){
foreach ($this->routes as $url => $action) {
if( $url == $_SERVER['REQUEST_URI'] ){
if(is_callable($action)) return $action();
$actionArr = explode('#', $action);
$controller = 'My\\system\\controllers\\'.$actionArr[0];
$method = $actionArr[1];
return (new $controller)->$method();
}
}
}
And I define the routes like this:
My\system\classes\Registry::get("Router")->add('/My/admin/','AdminController#index');
So when the URL SERVER/My/admin
is called the index
method of the AdminController
class is called.
My problem: How do I handle query strings?
I'd like to have a page with a form. On submit, the form gets sent to SERVER/My/admin/check
, i.e. to the check.php
page in the admin
folder.
I defined the route like this
My\system\classes\Registry::get("Router")->add('/My/admin/check','AdminController#check');
but the URL isn't found, of course, because the query string is attatched to the URL. How should I handle this best?
Upvotes: 0
Views: 1671
Reputation: 375
This example is from my project, how I handle this.
REQUEST_URI - The URI which was given in order to access this page; for instance, '/index.html'.
$full_router = $_SERVER['REQUEST_URI'];
strtok() splits a string (string) into smaller strings (tokens), with each token being delimited by any character from token.
$router = strtok($full_router, '?'); // This is how you can handle query parameters
Now you can match the URL with if statement
if($router === '/' ){
include('/pages/home.php');
}
Upvotes: 0
Reputation: 59699
Before checking $_SERVER['REQUEST_URI']
, remove everything past the first ?
, if one is present. Use that value to check if it matches with $url
. Something as simple as this will do the trick:
$request = $_SERVER['REQUEST_URI'];
if( ($pos = strpos($request, '?')) !== false) $request = substr($request, 0, $pos);
Any controllers that need to work with query parameters should be able to get them from $_GET
, or at worst $_SERVER['QUERY_STRING']
.
Upvotes: 2