-
Notifications
You must be signed in to change notification settings - Fork 13
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. Everyone controller must extend BaseController to be built into the URI Map.
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())
->setUserState(Vector {UserState::Pending});
}
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.
public static function getPath(): string {
return '/example';
}
Here we are specifying the path we want our controller to exist on. When we run the build tool, the will be used to dispatch the request here.
public static function getConfig(): ControllerConfig {
return (new ControllerConfig())
->setUserState(Vector {UserState::Pending});
}
Here we are building a configuration object for this controller. This can specify things like the title
displayed or the required user state or roles that the current user must possess to access the methods of this controller. You can find more information about the ControllerConfig here.
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 HTMP. 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