Creating a controller
Use themake:controller Ace command to create a new controller:
app/controllers/users_controller.ts:
Controller naming conventions
By default, controllers are:- Created in plural form (e.g.,
UsersControllerfor “User”) - Stored in
app/controllers/directory - Named with a
_controller.tssuffix
--singular flag to create a singular controller:
Defining controller methods
Add methods to your controller to handle different routes:Binding controllers to routes
Reference controllers in your routes using the string syntax or array syntax:String reference (recommended)
#controllers/ prefix is an import alias that maps to your app/controllers directory.
Array reference
Lazy-loaded controllers
For better performance, lazy-load controllers:Resourceful controllers
Create a controller with RESTful methods using the--resource flag:
API controllers
For API-only applications, use the--api flag to exclude create and edit methods:
Custom action controllers
Create a controller with specific methods:Nested controllers
Organize controllers in subdirectories:app/controllers/admin/users_controller.ts
Reference in routes:
Dependency injection
Controllers support dependency injection through constructor parameters:Accessing HttpContext properties
TheHttpContext object provides access to various request/response properties:
Best practices
Keep controllers focused
Keep controllers focused
Each controller should handle a single resource. If your controller is getting too large, consider splitting it into multiple controllers or extracting logic into services.
Use services for business logic
Use services for business logic
Controllers should be thin and delegate complex business logic to service classes. This makes your code more testable and maintainable.
Validate input in controllers
Validate input in controllers
Always validate user input using request validators before processing:
Use consistent naming
Use consistent naming
Follow RESTful naming conventions for controller methods:
index- List all resourcescreate- Show form to create a resourcestore- Create a new resourceshow- Show a specific resourceedit- Show form to edit a resourceupdate- Update a resourcedestroy- Delete a resource