Skip to content

Architecture Controllers

alsonkemp edited this page Sep 13, 2010 · 2 revisions

Controllers receive the request, manipulate Models and send the request onwards. A basic Controller looks something like:


import Turbinado.Controller
import App.Models.Page

index :: Controller ()
index = do pages <- findAll
setViewDataValue “pages-list” $ map (\p → (title p, _id p)) pages

show :: Controller ()
show = do id’ <- getSetting_u “id”
p <- find id’
setViewDataValue “page-title” (title p)
setViewDataValue “page-content” (content p)

All Controllers must import Turbinado.Controller. In addition, this controller uses the Page Model, so imports App.Models.Page. Since only one Model is imported, the import doesn’t have to be qualified; if more than one Model is imported, then the Model imports should be qualified (e.g. import qualified App.Model.Page as Page).

ViewData

The ViewData Environment value is intended to allow Controllers to send data to the View. The index function uses the ViewData to hold a list of tuples of title and _id. The View can then retrieve the values using getViewDataValue.

Only Typeable types (ie. instances of Typeable) can be stored as values in the ViewData. If you need to store a non-Typeable value in the ViewData, you must convert the value to a value which is an instance of Typeable. The most obvious way to do this is to convert your value to a String (since the View is going to display a string anyways).

Layout and View

After the Controller finished, the Layout is called (by default /App/Layouts/Default.hs). If the Controller would not like a Layout to be used, the Controller can call clearLayout to prevent a Layout being used with the View. This is useful when returning XML.

Controller Returns

Generally a Controller will work with a few Models, put together some ViewData for the View, and then return (). In this case, the Layout/View is called directly after the Controller returns.

However, if the Controller produces a valid, complete Response, then the Layout/View will not be called and the Controller-produced Response will be returned to the client. For example, the Controller can do redirectTo “/SomePage/SomeAction” and that will generate a valid HTTP 302 response.

Clone this wiki locally