I’ve been taking a lot of programming tests / challenges recently as I was in the market for a new [and hopefully exciting] opportunity to spend my time on. Because of this, I am full of new blog post ideas based on the questions / challenges asked. This week I’m going to discuss how to handle URL routing with PHP.
There is one major assumption here, it’s that all of your URIs route directly to a single script, for instance index.php
. I feel like setting this up is a bit out of scope as it’s a bit different depending on the web server you’re running. If there’s enough feedback that this should be included, I’ll go ahead and get it added, but until then, I’ll assume you can handle that part.
The next (not so major) assumption is that your URI structure will lend itself to a specific class structure. For the sake of example, a URI like /user/edit
will call the edit()
method on the User
class. We will be sure to check the existence of both while exploiting the fact that you can instantiate classes and request methods stored in strings.
$uri = explode('/', strtolower(substr($_SERVER['REQUEST_URI'], 1)));
$class = ucfirst($uri[0]);
$method = $uri[1];
try {
if (class_exists($class)) {
$object = new $class();
if (method_exists($object, $method)) {
$object->$method();
} else {
throw new Exception('Requested method does not exist.');
}
} else {
throw new Exception('Requested class does not exist.');
}
} catch (Exception $e) {
exit($e->getMessage());
}
PHPThis is obviously a very rudimentary example with less than ideal error handling. You can easily route the user to a URI for the error page or even push a 404 error to the browser. Another short coming is the fact that we are only handling URIs with 2 parts /first/second
, but you can set up handling for single part or 3+ part URIs if so desired. A lot of it depends on your application needs and how you want to set things up.
For anyone state side, I hope you had a great Memorial Day weekend! And for any service men & women turned coders, I thank you.