Mapping Routes to Controllers

PHP How To

Websites try to format their URLs to make them easier to remember instead of depending on the file that should handle that request. Also, all the requests go through the same file, index.php, regardless of their path. Because of this, we need to keep a map of the URL paths, and who should handle them.

images/articles/php/mapping-routes-controllers.jpg

Sometimes, you have URLs that contain parameters as part of their path, which is different from when they contain the GET or POST parameters. For example, to get the page that shows a specific book, you might include the ID of the book as part of the URL, such as /book/12 or /book/3. The ID will change for each different book, but the same controller should handle all of these requests.

To achieve this, we say that the URL contains an argument, and we could represent it by /book/:id, where id is the argument that identifies the ID of the book. Optionally, we could specify the kind of value this argument can take, for example, number, string, and so on.

Controllers, the ones in charge of processing requests, are defined by a method's class. This method takes as arguments all the arguments that the URL's path defines, such as the ID of the book. We group controllers by their functionality, that is, a BookController class will contain the methods related to requests about books.

The Router

The main goal is to receive a Request object, decide which controller should handle it, invoke it with the necessary parameters, and return the response from that controller.

Main method of router class, route, takes a Request object and returns a string, which is what you will send as output to the client. The router will execute the notFound method of the ErrorController, which will then return an error page.