Before I show you the complete definition of the router/dispatcher class mentioned in the previous segment, it’d be useful to specify the format that this class will expect to receive from a given URL. Basically, any request routed to the controller “index.php” file would have to match the following pattern: controllername/methodname/parametername As you can see, the format of the URL supplied to the dispatcher sticks pretty tightly to the standard used by many modern frameworks, where the first expected argument is the name of the controller to instantiate, followed by the name of any of its methods, and finally followed by an optional incoming argument. Naturally, it’d be easy to make the dispatcher accept more arguments, but for the sake of brevity it’ll follow only the above format. Having clarified that point, please look at the definition of the router/dispatcher class, which is as follows: <?php class Dispatcher { // dispatch request to the appropriate controller/method public static function dispatch() { $url = explode('/', trim($_SERVER['REQUEST_URI'], '/')); array_shift($url); // get controller name $controller = !empty($url[0]) ? $url[0] . 'Controller' : 'DefaultController'; // get method name of controller $method = !empty($url[1]) ? $url[1] : 'index'; // get argument passed in to the method $arg = !empty($url[2]) ? $url[2] : NULL; // create controller instance and call the specified method $cont = new $controller; $cont->$method($arg); } }// End Dispatcher class As seen above, the dispatcher class implements a single static method, called “dispatch()”, which is tasked with parsing the given URL, then instantiating the corresponding controller class (with the prefix “Controller” added to it), and finally calling the appropriate method with the supplied argument. Even though the functioning of this class isn’t bullet-proof and can be improved, it shows how to build a simple router/dispatcher class that accepts SEO-friendly URLs. Also, you should notice that the class assigns some default values to the controller and to its associated method if these don’t match the supplied URL. This means that if no controller matches the first URL segment, then a “DefaultController” class will be instantiated, while if no method matches the second part of the URL, an “index()” method will be called automatically. Pretty easy to grasp, right? At this point, the functionality of the MVC-based framework has been slightly expanded, since it’s been provided with the capability for routing and dispatching neatly-formatted user requests by means of a simple class. So, the next step that I’m going to take will be listing all of the framework’s source files, now that the construction of the dispatcher class has been completed. This will be done in the last segment of this tutorial, so go ahead and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|