7.3. Controller Variables

Manipulating a few special variables inside of your controller allows you to take advantage of some extra Cake functionality:

$name

PHP 4 doesn't like to give us the name of the current class in CamelCase. Use this variable to set the correct CamelCased name of your class if you're running into problems.

$uses

Does your controller use more than one model? Your FragglesController will automatically load $this->Fraggle, but if you want access to $this->Smurf as well, try adding something like the following to your controller:

var $uses = array('Fraggle','Smurf');

Please notice how you also need to include your Fraggle model in the $uses array, even though it was automatically available before.

$helpers

Use this variable to have your controller load helpers into its views. The HTML helper is automatically loaded, but you can use this variable to specify a few others:

var $helpers = array('Html','Ajax','Javascript');

Remember that you will need to include the HtmlHelper in the $helpers array if you intend to use it. It is normally available by default, but if you define $helpers without it, you'll get error messages in your views.

$layout

Set this variable to the name of the layout you would like to use for this controller.

$autoRender

Setting this to false will stop your actions from automatically rendering.

$beforeFilter

If you'd like a bit of code run every time an action is called (and before any of that action code runs), use $beforeFilter. This functionality is really nice for access control - you can check to see a user's permissions before any action takes place. Just set this variable using an array containing the controller action(s) you'd like to run:

class ProductsController extends AppController
{
    var $beforeFilter = array('checkAccess');

    function checkAccess()
    {
        //Logic to check user identity and access would go here....
    }

    function index()
    {
        //When this action is called, checkAccess() is called first.
    }
}

$components

Just like $helpers and $uses, this variable is used to load up components you will need:

var $components = array('acl');