Skip to content
Download

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.

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.

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.

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.

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.