Creating Controllers
A controller is a class that derives from mach::ControllerBase and groups related actions under a common route.
Define a Controller
Section titled “Define a Controller”Create a controller class for the part of your application you want to handle:
class UsersController final : public mach::ControllerBase {public: inline static constexpr std::string_view route = "/users";
mach::Reply<> index() { return noContent(); }
static void configure(mach::ControllerBuilder<UsersController>& builder) { builder.mapGet("/", &UsersController::index); }};Every controller defines a base route. Routes mapped by the controller are relative to that base route.
In this example, the controller route is:
/usersand the index action is mapped to:
/Together, they handle:
GET /users/Keeping configure() at the end of the class leaves the controller’s actions together and makes the route configuration easy to find.
ControllerBuilder
Section titled “ControllerBuilder”The configure() function receives a mach::ControllerBuilder specialized for the controller:
static void configure(mach::ControllerBuilder<UsersController>& builder) { builder.mapGet("/", &UsersController::index);}ControllerBuilder connects controller actions to HTTP methods and routes.
The controller type is supplied as the template argument:
mach::ControllerBuilder<UsersController>This allows the builder to map routes directly to member functions of UsersController, such as:
builder.mapGet("/", &UsersController::index);The route passed to the builder is relative to the controller’s base route.
You will take a closer look at action mapping in the next guide.
Generate a Controller
Section titled “Generate a Controller”The Mach CLI can create the controller file for you.
Run:
mach generate controller usersMach generates a UsersController in your project’s controllers directory.
Controller names are normalized automatically, so you can provide either a resource name or a controller name:
| Input | Generated controller |
|---|---|
users |
UsersController |
usersController |
UsersController |
USERS |
UsersController |
Register the Controller
Section titled “Register the Controller”A controller must be registered with the application builder:
mach::AppBuilder builder;
builder.addController<UsersController>();
auto app = builder.build();Registered controllers are configured when the application is built. Controllers that are not registered are not included in the application.
Organizing Controller Files
Section titled “Organizing Controller Files”A typical project keeps controllers in a dedicated directory:
src/└── controllers/ └── UsersController.hppThis keeps controller definitions separate from application startup and makes larger applications easier to navigate.
Next, you’ll learn how to define and map controller actions.