1. Controller Functions

Important

While this section will treat most of the oft-used functions in Cake's Model, its important to remember to use http://api.cakephp.org for a full reference.

1.1. Interacting with your Views

  • set($var, $value)

    • This function is the main way to get data from your controller to your view. You can use it to hand over anything: single values,whole arrays, etc. Once you've used set(), the variable can be accessed in your view: doing set('color', 'blue') in your controller makes $color available in the view.

  • validate()

    • Returns the number of errors generated by an unsuccessful save.

  • validateErrors()

    • Validates a model data according to the model's defined validation rules. For more on validation, see Chapter 10.

  • render($action = null, $layout = null, $file = null)

    • You may not often need this function, because render is automatically called for you at the end of each controller action, and the view named after your action is rendered. Alternatively, you can call this function to render the view at any point in the controller logic.

1.2. User Redirection

  • redirect($url)

    • Tell your users where to go using this function. The URL passed here can be a Cake interal URL, or a fully qualified URL (http://...)

  • flash($message, $url, $pause = 1)

    • This function shows $message for $pause seconds inside of your flash layout (found in app/views/layouts/flash.thtml) then redirects the user to the specified URL.

1.3. Controller Callbacks

Cake controllers feature a number of callbacks you can use to insert logic before or after important controller functions. To utilize this functionality, declare these functions in your controller using the parameters and return values detailed here.

  • beforeFilter()

    • Called before every controller action. A useful place to check for active sessions and check roles.

  • afterFilter()

    • Called after every controller action.

  • beforeRender()

    • Called after controller logic, and just before a view is rendered.

1.4. Other Useful Functions

While these are functions part of Cake's Object class, they are also available inside the Controller:

  • requestAction($url, $extra = array())

    • This function calls a controller's action from any location and returns the rendered view. The $url is a Cake URL (/controllername/actionname/params). If the $extra array includes a 'render' key, AutoRender is automatically set to true for the controller action.

  • log($msg, $type = LOG_ERROR)

    • You can use this function to log different events that happen within your web application. Logs can be found inside Cake's /tmp directory.