Understanding Controllers
Controllers provide a structured way to organize related endpoints in a Mach application.
Instead of defining every endpoint directly on the application:
app.mapGet("/users", [] { return mach::ok("Users");});
app.mapGet("/users/{id:int}", [](mach::Context& context) { const int id = context.request.routeParam<int>("id");
return mach::ok(id);});you can group related request handling inside a controller.
Why Use Controllers?
Section titled “Why Use Controllers?”As an application grows, defining every endpoint directly in main.cpp can make routing and request handling difficult to organize.
Controllers let you group endpoints that belong to the same part of your application. For example, operations related to users can live in a UsersController, while operations related to products can live in a ProductsController.
This keeps endpoint logic organized and separates it from application configuration.
ControllerBase
Section titled “ControllerBase”Mach controllers derive from mach::ControllerBase:
class UsersController : public mach::ControllerBase { // ...};ControllerBase provides the functionality used by controllers to define actions and produce responses.
The details of defining and registering a controller are covered in the next guide.
Controllers and Actions
Section titled “Controllers and Actions”Endpoints defined by a controller are called actions.
A controller can contain multiple actions for handling different requests. For example, a UsersController might contain actions for:
- retrieving all users
- retrieving a specific user
- creating a user
- updating a user
- deleting a user
Each action can be associated with its own HTTP method and route.
When to Use Controllers
Section titled “When to Use Controllers”Controllers are useful when you want to organize related request handling into dedicated classes.
For small applications, mapping endpoints directly on the application may be all you need. As an application grows, controllers provide a convenient way to keep related functionality together.
Next, you’ll create and register your first controller.