Controllers

It may be enough to write closure to handle your route for a small application, but when your application starts growing it could be useful to organize them. This is where Controllers enter in the dance floor.

Controllers are attached to one or many routes and are the common point of interaction between your models, views and any other services you may need.

Controllers only job is to respond to an HTTP request. Do not use them internally by requiring them inside different files.

Creating Controllers

To create a new controller, make use of the make:controller command.

> adonis make:controller User --type http # HTTP Controller
> adonis make:controller User --type ws   # WS Controller
> adonis make:controller Admin/User       # Will use an Admin subfolder

This command will create a file in the App/Controllers/{TYPE} folder with some boilerplate code.

You can use the --resource flag to create a resourceful controller.
app/Controllers/Http/UserController.js
'use strict'

class UserController {
}

module.exports = UserController

Using a Controller

A controller can be only accessed from a route. This is done by referencing them as a String in your route definition.

Route.get(url, 'UserController.index')

The part before the dot (.) is a reference to the controller file. It is by default namespaced to App/Controllers/Http. The second part is the name of the method you want to call inside this controller.

// app/Controllers/Http/UserController -> index()
Route.get(url, 'UserController.index')

// app/Controllers/Http/Admin/UserController -> store()
Route.post(url, 'Admin/UserController.store')

// app/MyOwnControllers/UserController -> index()
Route.post(url, 'App/MyOwnControllers/UserController.index')

Since these methods are route handlers, they will receive as an argument the HTTP Context.

'use strict'

class UserController {
  index ({ request, response }) {
    //
  }
}

module.exports = UserController