In reality, making the front controller bootstrap the dispatcher module mentioned in the previous section is reduced to writing one single line of code. It’s really that easy, believe me. To demonstrate this, below I included the finished version of the controller, which is now also capable of intercepting exceptions through a “try-catch” block. Look at the completed definition of the “index.php” file: <?php // framework’s front controller // specify parameters for autoloading classes spl_autoload_register(NULL, FALSE); spl_autoload_extensions('.php'); spl_autoload_register(array('Autoloader', 'load')); // define custom ClassNotFoundException exception class class ClassNotFoundException extends Exception{} // define Autoloader class class Autoloader { // attempt to autoload a specified class public static function load($class) { if (class_exists($class, FALSE)) { return; } $file = $class . '.php'; if (!file_exists($file)) { eval('class ' . $class . '{}'); throw new Exception('File ' . $file . ' not found.'); } require_once($file); unset($file); if (!class_exists($class, FALSE)) { eval('class ' . $class . '{}'); throw new ClassNotFoundException('Class ' . $class . ' not found.'); } } } // handle request and dispatch it to the appropriate controller try{ Dispatcher::dispatch(); } catch (ClassNotFoundException $e){ echo $e->getMessage(); exit(); } catch (Exception $e){ echo $e->getMessage(); exit(); }// End front controller Unquestionably, at this point the front controller looks much more useful, since it can now autoload classes, catch exceptions, and most important, bootstrap the corresponding dispatcher module through this single line of code: Dispatcher::dispatch(); Obviously, this means that the dispatcher is a class that has that same name, and that it also implements a static method called “dispatch().” However, if you’re eager and want to see how this class looks, then I suggest you take a deep breath and relax, since the development of the dispatcher will be discussed in depth in the next tutorial. Meanwhile, feel free to tweak all of the example code shown in this article, which might be pretty useful for enhancing the capabilities of the front controller file coded before. Final thoughts In this introductory chapter of the series, I developed the first module of this MVC-driven framework, which happens to be a front controller. As you saw for yourself, by combining this component and a basic .htaccess file it’s possible to route all of the HTTP requests to the still-undefined dispatcher class. But the wait won’t be long at all, as this class will be built in the next installment of this series. Now you don’t have any excuses to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|