Instead of specifying all of your request handling logic as closures in your route files, you might want to use "controller" classes to arrange this activity. Controllers can use a single class to bundle together similar request processing code. A UserController
class, for example, may manage all user-related inbound requests, such as viewing, creating, updating, and removing users. Controllers are kept in the app/http/controllers
directory by default.
Let's take a look at a basic controller in action. It's worth noting that the controller extends the OstroJS base controller class app/http/controllers/controller
:
const Controller = require('~/app/http/controllers/controller');
const User = require('~/app/models/user')
class UserController extends Controller {
async show({view,params}) {
view('user.profile', {
'user' : await User.findOrFail(params.id)
});
}
}
module.exports = UserController
This controller method's route can be defined as follows:
route.get('/user/:id', 'userController::show');
The show
method on the app/http/controllers/userController
class method is called when an incoming request matches the specified route URI, and the route parameters are passed to the method.