Chapter 7. Controllers

Table of Contents

1. Controller Functions
1.1. Interacting with your Views
1.2. User Redirection
1.3. Controller Callbacks
1.4. Other Useful Functions
2. Controller Variables

A controller is used to manage the logic for a certain section of your application. Most commonly, controllers are used to manage the logic for a single model. For example, if you were building a site that manages a video collection, you might have a VideoController and a RentalController managing your videos and rentals, respectively. In Cake, controller names are always plural.

Your application's controllers are classes that extend the Cake AppController class, which in turn extends a core Controller class. Controllers can include any number of actions: functions used in your web application to display views.

AppController class can be defined in /app/app_controller.php and it should contain methods that are shared between two or more controllers. It itself extends the Controller class which is a standard Cake library.

An action is a single functionality of a controller. It is run automatically by the Dispatcher if an incoming page request specifies it in routes configuration. Returning to our video collection example, our VideoController might contain the view(), rent(), and search() actions. The controller would be found in /app/controllers/videos_controller.php and contain:

class VideosController extends AppController
{
    function view($id)
    {
        //action logic goes here..
    }

    function rent($customer_id, $video_id)
    {
        //action logic goes here..
    }

    function search($query)
    {
        //action logic goes here..
    }
}

You would be able to access these actions using the following example URLs:

http://www.example.com/videos/view/253
http://www.example.com/videos/rent/5124/0-235253
http://www.example.com/videos/search/hudsucker+proxy

But how would these pages look? You would need to define a view for each of these actions - check it out in the next chapter, but stay with me: the following sections will show you how to harness the power of the Cake controller and use it to your advantage. Specifically, you'll learn how to have your controller hand data to the view, redirect the user, and much more.