I'm currently putting together a little mvc framework for practice, I have a bit of laravel experience so it is loosely based on that. I've made a router that simply returns a specified view for the url that you set.
Now I've also made controller that splits the url and uses the first part after the base url as controller and second part as action. This loads a file corresponding with the controller and a method within that file corresponding with the action.
So if the url is something like: url.com/users/index it will load a UsersController.php file and look for the index() method within that file.
Now I'm wondering with is the exact difference between a controller and a router? It it like a specified? Wherein a router is just a little bit simpler and just reacts to an exact given url and a router chops it up and has a little more depth?
What I currently have seems to overlap quite a bit.
The controller sits between the model and the view. It communicates with both to make a response to a request.
The router chooses which controller (and which method on that controller) handles the request. For example it might decide the request 'product/view/123' should call the ProductController's View methods passing 123 as a parameter.
A router might also convert urls. Instead of using, like you said, method and action in the url. You could also have www.example.com/members. And the router would convert it to UsersController's Index method. This allows the user of 'pretty' urls to map to nice logically named controllers.
(Presuming that router does not refer to network hardware or wood working tool!)
The router takes the request and decides which controller/controller methods will handle the request.
The controller accepts the requests and handles it!
Now I've also made controller that splits the url and uses the first part after the base url as controller and second part as action. This loads a file corresponding with the controller and a method within that file corresponding with the action.
This isn't really a controller (as far as MVC is concerned) it is part of the routing.
For example take the [GET] uri: example.com/article/view/123 The MVC router will parse the uri and find the following segments
By default most routers would now instantiate the articleController
and call its view
method passing in 123
as a parameter. (You could alternatively have some getUriSegment(segmentIdx)
method, that's a design choice for your framework.)
The ArticleController
would have a view
method with an $articleId
parameter. This method would probably do something like: get the specified article (from a db via a model for example) and then display it (probably by returning a view which has been given the article returned by the model)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With