Sunday, June 5, 2011

Modifying the FrontController to include the View Layer



Last time, what we did is to build a front controller which will be able to interpret the URL to invoke certain objects (controllers) and the functions of these controllers.

Yeah we are missing something. That is the view section. The view section is equally vital because it displays objects handed to it by the controller. Of course, the view section is styled according to the taste of the client/user. This can be done using CSS.

Anyway, the view section contains the least logic. As the name connotes, it is used to print data to the end user. But how can we include that to the FrontController? That's easy actually. Just add these lines of code to FrontController and BOOM! you got your view section included in the application.

$view = APP_DIR . "/" . $page . "/" . $action . ".php"; if(!is_file($view)){ exit("Severe: View section is not found!"); } include $view;

Modifying now the FronController.php will result to the code below.

<?php class FrontController{ public static function instance(){ if(!defined("APP_DIR")){ ext("Severe: Cannot proceed without access to application directory."); } } public function redirect(){ $page = !empty($_GET["page"]) ? $_GET["page"] : "home"; $action = !empty($_GET["action"] ? $_GET["action"] : "default"; $object = ucfirst($page) . "Controller"; $file = APP_DIR . "/" . $page . "/" . $object . ".php"; if(!is_file($file)){ exit("Severe: Controller not found!"); } require_once $file; $method = "do" . ucfirst($action); $controller = new $object(); if(!method_exists($controller, $method)){ exit("Severe: Action not found."); } $controller->$method();
//06-06-2011 - include view - start add $view = APP_DIR . "/" . $page . "/" . $action . ".php"; if(!is_file($view)){ exit("Severe: View section is not found!"); } include $view; //06-06-2011 - include view - end add
exit(0); } } ?>


You may now separate your view sections by creating a folder equal to the $page name and the view file name equal to the controller's function. Let's see, our previous sample is AccountController. Create a folder name on application directory (APP_DIR) called account. In that folder create a php file with file name printFNameView.php. Style it as you may want. When you invoke the address index.php?page=account&action=printFName,


the view section (printFName.php) will be displayed. Complete code will be provided with samples soon.

Learn More:

No comments:

Post a Comment

There was an error in this gadget