In this episode, we focus on cleaning up our routing logic by moving away from inline closures and introducing controllers. Initially, we notice that our routes file is starting to look a bit messy, especially as more routes and logic get added. The solution? Move our logic into separate controller classes to keep things organized and scalable.
We start by creating a new folder structure where our controllers will live (usually something like Http/Controllers
), and then we create a simple HomeController
class. We set up the magic __invoke
method so our controller can handle incoming requests. We also go through how to use this controller in our routes file by referencing its namespace, and troubleshoot the common errors that come up when PHP can't find the controller or it's not properly callable.
Next, we revisit the functionality from our original closure routes and show how to handle responses within the controller, writing out some basic HTML. To make things more dynamic, we find out how to access the query string parameters from the incoming request — for example, displaying a name that's passed in the URL.
Finally, we touch on how form data would be handled similarly, accessing it through the request's parsed body, which will be extra helpful when we get to things like registration forms. By the end of the episode, we've successfully refactored our simple route into a controller and set a foundation for cleaner code as our app grows.