Skip to content

Controllers ​

Introduction ​

Closures are fine for small routes, but as an application grows you will want to group related handling logic into classes. A controller is a plain class whose methods receive the Request and return a result. The router resolves the class through the container for each request, so a controller can have its own dependencies.

In a scaffolded application controllers live in src/controllers/, and the generated make:controller command creates them (add the resource flag to get all seven resource methods).

Writing controllers ​

Extend the Controller base class and add methods. Extending it is a convention, not a requirement: any class works. The base class gives you one stable place to hang application wide helpers.

ts
import { Controller, Response } from '@plinthjs/http'
import type { Request } from '@plinthjs/http'

export class UserController extends Controller {
  index() {
    return [{ id: 1, name: 'Ada' }] // an array becomes JSON
  }

  show(req: Request) {
    return Response.json({ id: req.param('id') })
  }
}

Point a route at a method with a [Controller, 'method'] pair:

ts
import { Router } from '@plinthjs/http'

const router = new Router()
router.get('/users', [UserController, 'index'])
router.get('/users/{id}', [UserController, 'show']).name('users.show')

A method may be async. It returns the same kinds of values as a closure: a Response, a string (HTML), an object (JSON) or nothing (204). If the method named in the route does not exist, the request fails with a 500 that names the controller and method.

The application base controller ​

The scaffolder generates src/controllers/controller.ts, an abstract class that extends the framework's Controller. Your controllers extend that one, so you can add shared helpers in a single place:

ts
import { Controller as PlinthController } from '@plinthjs/http'

export abstract class Controller extends PlinthController {}

Middleware is declared on the route or group, not on the controller. See Middleware.

Single action controllers ​

If a controller handles exactly one action, name the method __invoke and pass the bare class to the route. A one element tuple works too.

ts
import type { Request } from '@plinthjs/http'
import { Controller } from '@plinthjs/http'

export class ShowDashboard extends Controller {
  __invoke(req: Request) {
    return { user: req.param('user') ?? null }
  }
}

router.get('/dashboard', ShowDashboard)
router.get('/dashboard/{user}', [ShowDashboard]) // same thing

The kernel tells a class from a closure by checking for an __invoke method on the class prototype (inherited methods count), so a controller that extends a base class works. Arrow functions and plain functions are always closures.

Resource controllers ​

router.resource() maps the conventional CRUD verbs onto controller methods named index, create, store, show, edit, update and destroy. See Resource routes for the full table and the options for limiting, renaming and nesting them.

ts
export class PhotoController extends Controller {
  index() {
    return []
  }
  store(req: Request) {
    return Response.json(req.only(['title']), 201)
  }
  show(req: Request) {
    return { id: req.param('photo') }
  }
  update(req: Request) {
    return { updated: req.param('photo') }
  }
  destroy(req: Request) {
    return null
  }
}

router.resource('photos', PhotoController).only(['index', 'store', 'show', 'update', 'destroy'])
router.apiResource('photos', PhotoController) // no create or edit

You only need to implement the methods the routes you register will call. Singleton resources use show, edit, update and destroy the same way.

Dependency injection ​

When the kernel has a container, it calls container.make(ControllerClass) for every request, so each request gets a fresh controller instance (unless you bind the controller as a singleton). Classes with no binding are constructed with no arguments. JavaScript has no constructor parameter reflection, so you declare how a controller's dependencies are built by binding it:

ts
import { Container } from '@plinthjs/core'
import { HttpKernel } from '@plinthjs/http'

class UserRepository {
  find(id: string) {
    return { id, name: 'Ada' }
  }
}

class UserController extends Controller {
  private readonly users: UserRepository

  constructor(users: UserRepository) {
    super()
    this.users = users
  }

  show(req: Request) {
    return this.users.find(req.param('id')!)
  }
}

const app = new Container()
app.singleton(UserRepository)
app.bind(UserController, (c) => new UserController(c.make(UserRepository)))

const kernel = new HttpKernel(router, { container: app })
// GET /users/3 => {"id":"3","name":"Ada"}

Pass the container to the kernel through the container option. Without one the kernel simply calls new Controller(). See Service container for bindings and Providers for where to register them in an application.

Handling the request ​

A controller method receives the Request as its only argument. Route parameters, query string, body, files and headers are all read from it, see Requests. The route's bound model, when you registered a binding, is read with req.route('name'), see Route model binding.

The return value is turned into a response by the same rules as a closure, so use Response helpers from Responses when you need control over the status, headers or redirects.

The handle() method ​

You may notice commands in the console package expose a handle() method. That is a different concept. For HTTP, the kernel's own kernel.handle(request) is what runs the whole pipeline (global middleware, matching, route middleware, your controller, exception rendering) and returns a Response. Call it directly to test a controller through the real router without any network:

ts
import { HttpKernel, Request } from '@plinthjs/http'

const kernel = new HttpKernel(router, { container: app })
const res = await kernel.handle(new Request({ method: 'GET', url: '/users/3' }))
res.status // => 200
res.body // => '{"id":"3","name":"Ada"}'

See Testing.

Released under the MIT License.