Other Parts:
In the previous article, we covered handling simple routes with basic functionality, specifically for GET
requests. Now, it's time to enhance our router to handle multiple HTTP methods. Before diving into that, let's first explore the concept of controllers. Controllers act as an intermediary between the routes and the views, encapsulating the logic and handling the requests. They provide a structured way to organize and manage the functionality of your application.
Controller:
A controller is a class that takes care of handling the request and performs necessary operations or processes before rendering the page if required. In certain cases, specific routes may require additional tasks such as fetching data from a database, uploading images, or performing other operations. The controller encapsulates this functionality, allowing for a modular and organized approach to handling different routes and their associated tasks.
Let's create our first controller:
The controller is very simple, it creates a variable and passes it to the view.
We have now to update the Router
to require the router instead of the view.
First, let's add the render method to handle controller importing.
Now, the whole class will become:
Update web.php
file:
Let's add $name
variable to home view:
The result:
![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687650119681/d9181db8-c67d-41da-8710-cd3e81c1996e.png align="center")
Conclusion:
This is essentially the controller. We will later add a base Controller
class to avoid duplicating the __construct
method.
See you in the next one!