# Controller
Instead of defining all of your request handling logic as closures in your route files, you can organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the App/Http/Controllers directory.
# Creating Controllers
# Basic Controllers
Let's take a look at an example of a basic controller. To create a new controller called UserController, use the maker command for controller:
node maker make-controller UserController
We will have:
"use strict";
class UserController {
//
}
module.exports = UserController;
Let's add some basic feature to our UserController
const UserModel = require("@model/UserModel");
'use strict'
class UserController{
show = async(req,res,next){
try{
let id = req.params.id;
let user = await UserModel::query().findById(id);
return res.status(200).json(user);
}catch(error){
next(error)
}
}
}
module.exports = UserController
You can define a route to this controller method like so:
Route.get("/user/:id", "UserController@show");
# Resource Controllers
ExpressWebJs resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for "users" stored by your application. Using the make-controller Maker command, we can quickly create such a controller:
node maker make-controller UserController -r
This command will generate a controller at App/Http/Controllers/UserController.js. The controller will contain a method for each of the available resource operations.
# Dependency Injection & Controllers
ExpressWebJs service container is used to resolve all ExpressWebJs controllers. As a result, you are able to type-hint any dependencies you've registered in the App/Providers/AppServiceProvider.js register method into your controller constructor. The declared dependencies will automatically be resolved and injected into the controller instance:
First register your service in App/Providers/AppServiceProvider.js register method:
const ioc = require("expressweb-ioc");
class AppServiceProvider {
/**
* Register application services.
*/
static register() {
return {
MyService: ioc.asClass("App/Service/MyService", "SINGLETON"),
};
}
}
module.exports = AppServiceProvider;
We can now inject MyService into our UserController constructor:
"use strict";
class UserController {
constructor({ MyService }) {
this.service = MyService;
}
}
module.exports = UserController;
← Validation Request →