I'm trying to figure out if its bad practice to initiate a controller from within a router class. From what little I have been able to find about this, some say that the router shouldn't handle instantiating controllers. Below is how I started to develop my router class.
Example(note I'm omitting alot for the sake of typing.)
class Router {
private $url, $controller;
public function __construct($url)
{
$this->url = $url;
$this->map(); /* maps url to controller and action*/
/*dispatch controller*/
$this->dispatch();
}
private function dispatch()
{
$controller = new $this->controller();
$controller->executeAction();
}
}
To answer you question I'd so no it violates separation of concerns. The router shouldn't be worried what controller handles it's request, or rather how that controller came into being. It only needs to know that at some point, even in the event of a 404 that some controller will handle it.
Now injecting a controller into the route would be ok, then you could prototype it as an interface like so,
public function dispatch(ControllerInterface $Controller){
.....
}
otherwise you have to much hard linking, to much dependency, what if you need a second controller?
For example say you need an admin controller and a public controller, and a members controller. Do you then build 3 routers.
Personally the approach I am planning for a project I am working on is to use an event driven system, where there will be a group of controllers assigned by default as in a traditional routing system ( class/method/args... ) , say a controller folder will be searched for them. Other wise a controller will register itself to listen for a particular http request. So the flow is a bit like this.
Are there any registered listeners for this request, if no are there any controllers in our controller folder that match the routing schema, and at the very end is a 404 controller that will handle any request.
If any of these catch it the event ( that's being listened to is terminated ). The advantage of this over a purely hard wired route is, say I want to make a payment plugin, which needs a payment page, how do I put that in the controller folder as a third party vender? This way one only needs activate the plugin, which registers for the "payments" route, and listens within it's own package.
Maybe this is not a concern of you project but it's something to think about.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments