I always been curious on how to build great application with proper routing to my controllers, but after seeing some sources of applications like Xenforo, Joomla, it seems completely different, and mostly I can't understand them.
From my understanding the user sends a request to the web-server, the controller's job is to get the request, check out how is the request sending (to check if the request was done via XHR, etc) and then checking the sent GET requests and get the correct controller for the sent request, which will do the rest of the work.
This is what I exactly do currently, but I feel like my way is a bit not 'dynamic' as I have to put each controller's object into the switch statement.
This is my router class:
namespace library;
/**
* Controllers
*/
use library\controllers\Controller,
library\controllers\ChatController;
/**
* Class Router
* @package library
*/
class Router {
private $instance;
public function __construct(AsynChat $instance) {
$this->instance = $instance;
}
/**
* Deciding which routing channel to take.
*/
public function processRoutingChannel() {
if ($this->instance->getRequest()->isXHR()) {
$this->routeXHR();
return;
}
$this->route();
}
/**
* Handling a regular, visual web request.
*/
private function route() {
$request = $this->instance->getRequest();
$controller = null;
switch ($request->getGet(Config::$DEFAULT_GET_DIRECTOR)) {
default:
$controller = new ChatController($this->instance);
break;
}
$controller->register();
$controller->initializeTemplate();
}
/**
* Handling response for an AJAX request header.
* returns the needed data.
*/
private function routeXHR() {
$request = $this->instance->getRequest();
$controller = null;
switch ($request->getPost(Config::$DEFAULT_XHR_DIRECTOR)) {
case "chat":
$controller = new ChatController($this->instance);
break;
default:
break;
}
$controller->initializeAjaxResponse();
}
}
I simply create a new router object and add the main object to it, which contains all the objects like request, database, session and so on.
And then I do $router->processRoutingChannel();
I am pretty sure the way I am doing this, is pretty 'Ghetto'.
Is there anything wrong you can tell? What is the best way to do so?
In my controllers, register()
method makes the controller start doing it's job, and initializeTemplate()
method forces the controller to draw the page, as in include the template.