-
Notifications
You must be signed in to change notification settings - Fork 0
Nova: Controllers
Controllers are created for each requests and destroyed after processing the request.
Registering controllers in your application This is very simple, although controllers are not registered automatically, there are a lot of configuration options available.
Creating controller contexts (click here to see live example): tl;dr:
class WebApplication : public IWebApplication
{
public:
WebApplication(const ApplicationInitContext& context)
: IWebApplication(context)
{ }
void RegisterControllers()
{
auto& cf = GetContext().GetControllerFactory();
cf.CreateContext<HomeController>("home", "/api")
.RouteAction<&HomeController::Index>(Method::Get, "index")
.RouteAction<&HomeController::Get>(Method::Get, "get", "[params]")
.RouteAction<&HomeController::Login>(Method::Get, "login")
.RouteAction<&HomeController::Logout>(Method::Get, "logout");
}
};
Lifetime of controllers
On initialization controller registration must be done. This is required to prepare the controller metadata (e.g. actions, etc..).
When a request is made, routing system processes a url and gives us controller/action, which is used to find the requested controller context with a needed action, if controller context is found a new instance of Controller object is created and pre-/post-filters are executed, every controller gets destroyed after request processing.
Each controller contains the information about request itself, identity session and miscellaneous data. See here.
Example of controller class:
class HomeController : public Nova::IController
{
public:
NOVA_CONTROLLER(HomeController);
void Index()
{
bool isAuthenticated = GetUserManager().IsUserAuthenticated(Session);
if (isAuthenticated)
{
ObjectResult result("Perhaps");
Ok(&result);
}
else
{
ObjectResult result("No");
NotAuthorized(&result);
}
}
void Doges()
{
PhysicalFile("doges.html");
}
};