Skip to content
Robert Lynch edited this page Jan 25, 2016 · 6 revisions

Controllers

A Controller in Nucleus is the core of the logic for a request. They use Models to interact with the database, and finish by generating a View. Every controller must extend BaseController to be built into the URI Map.

Anatomy of a Controller

Here's an example controller:

<?hh // strict
class ExampleController extends BaseController {
  public static function getPath(): string {
    return '/example';
  }

  public static function getConfig(): ControllerConfig {
    return (new ControllerConfig())
      ->addCheck(function(): bool {
        return true;
      });
  }

  public static function get(): XHPRoot {
    return
      <nucleus:example />;
  }

  public static function post(): void {
    UserMutator::delete(Session::getUser()->getID());
    Route::redirect(FrontpageController::getPath());
  }
}

Let's break this down and go over what each function is doing.

getPath()

public static function getPath(): string {
  return '/example';
}

Here we are specifying the path we want our controller to exist on. For this example, when we run the build tool, the generated URI map will specify to dispatch all requests on /example to ExampleController.

getConfig()

public static function getConfig(): ControllerConfig {
  return (new ControllerConfig())
    ->addCheck(function(): bool {
      return true;
    });
}

Here we are building a configuration object for this controller. This can specify things like the title displayed, or we can add custom checks which must evaluate to true to display this page. There are pre-configured checks available in Auth.php. You can find more information about the ControllerConfig here.

get() / post()

public static function get(): XHPRoot {
  return
    <nucleus:example />;
}

public static function post(): void {
  UserMutator::delete(Session::getUser()->getID());
  Route::redirect(FrontpageController::getPath());
}

Here are our action methods. By specifying a get method, we are saying this controller can handle HTTP get requests on the path this controller lives on. Here, our get function is returning an XHP object. This will get inserted into the page template and rendered out at HTML. The post function is returning void; this means that it will not send a response back to the user. Alternatively, an action method can also return a Map or Vector, which gets rendered out as JSON

Clone this wiki locally