Find file
Fetching contributors…
Cannot retrieve contributors at this time
815 lines (608 sloc) 30.7 KB

Controllers

Controllers are the 'C' in MVC. After routing has been applied and the correct controller has been found, your controller's action is called. Your controller should handle interpreting the request data, making sure the correct models are called, and the right response or view is rendered. Controllers can be thought of as middle man between the Model and View. You want to keep your controllers thin, and your models fat. This will help you more easily reuse your code and makes your code easier to test.

Commonly, a controller is used to manage the logic around a single model. For example, if you were building a site for an online bakery, you might have a RecipesController managing your recipes and an IngredientsController managing your ingredients. However, it's also possible to have controllers work with more than one model. In CakePHP, a controller is named after the primary model it handles.

Your application's controllers extend the AppController class, which in turn extends the core :php:class:`Controller` class. The AppController class can be defined in /app/Controller/AppController.php and it should contain methods that are shared between all of your application's controllers.

Controllers provide a number of methods that handle requests. These are called actions. By default, each public method in a controller is an action, and is accessible from a URL. An action is responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well.

The App Controller

As stated in the introduction, the AppController class is the parent class to all of your application's controllers. AppController itself extends the :php:class:`Controller` class included in the CakePHP core library. AppController is defined in /app/Controller/AppController.php as follows:

class AppController extends Controller {
}

Controller attributes and methods created in your AppController will be available to all of your application's controllers. Components (which you'll learn about later) are best used for code that is used in many (but not necessarily all) controllers.

While normal object-oriented inheritance rules apply, CakePHP does a bit of extra work when it comes to special controller attributes. The components and helpers used by a controller are treated specially. In these cases, AppController value arrays are merged with child controller class arrays. The values in the child class will always override those in AppController.

Note

CakePHP merges the following variables from the AppController into your application's controllers:

Remember to add the default Html and Form helpers if you define the :php:attr:`~Controller::$helpers` property in your AppController.

Also remember to call AppController's callbacks within child controller callbacks for best results:

public function beforeFilter() {
    parent::beforeFilter();
}

Request parameters

When a request is made to a CakePHP application, CakePHP's :php:class:`Router` and :php:class:`Dispatcher` classes use :ref:`routes-configuration` to find and create the correct controller. The request data is encapsulated in a request object. CakePHP puts all of the important request information into the $this->request property. See the section on :ref:`cake-request` for more information on the CakePHP request object.

Controller actions

Controller actions are responsible for converting the request parameters into a response for the browser/user making the request. CakePHP uses conventions to automate this process and remove some boilerplate code you would otherwise need to write.

By convention, CakePHP renders a view with an inflected version of the action name. Returning to our online bakery example, our RecipesController might contain the view(), share(), and search() actions. The controller would be found in /app/Controller/RecipesController.php and contain:

# /app/Controller/RecipesController.php

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

    public function share($customerId, $recipeId) {
        //action logic goes here..
    }

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

The view files for these actions would be app/View/Recipes/view.ctp, app/View/Recipes/share.ctp, and app/View/Recipes/search.ctp. The conventional view file name is the lowercased and underscored version of the action name.

Controller actions generally use :php:meth:`~Controller::set()` to create a context that :php:class:`View` uses to render the view. Because of the conventions that CakePHP uses, you don't need to create and render the view manually. Instead, once a controller action has completed, CakePHP will handle rendering and delivering the View.

If for some reason you'd like to skip the default behavior, both of the following techniques will bypass the default view rendering behavior.

  • If you return a string, or an object that can be converted to a string from your controller action, it will be used as the response body.
  • You can return a :php:class:`CakeResponse` object with the completely created response.

When you use controller methods with :php:meth:`~Controller::requestAction()`, you will often want to return data that isn't a string. If you have controller methods that are used for normal web requests + requestAction, you should check the request type before returning:

class RecipesController extends AppController {
    public function popular() {
        $popular = $this->Recipe->popular();
        if (!empty($this->request->params['requested'])) {
            return $popular;
        }
        $this->set('popular', $popular);
    }
}

The above controller action is an example of how a method can be used with :php:meth:`~Controller::requestAction()` and normal requests. Returning array data to a non-requestAction request will cause errors and should be avoided. See the section on :php:meth:`~Controller::requestAction()` for more tips on using :php:meth:`~Controller::requestAction()`

In order for you to use a controller effectively in your own application, we'll cover some of the core attributes and methods provided by CakePHP's controllers.

Request Life-cycle callbacks

CakePHP controllers come fitted with callbacks you can use to insert logic around the request life-cycle:

In addition to controller life-cycle callbacks, :doc:`/controllers/components` also provide a similar set of callbacks.

Controller Methods

For a complete list of controller methods and their descriptions visit the CakePHP API.

Interacting with Views

Controllers interact with views in a number of ways. First, they are able to pass data to the views, using :php:meth:`~Controller::set()`. You can also decide which view class to use, and which view file should be rendered from the controller.

Rendering a specific view

In your controller, you may want to render a different view than the conventional one. You can do this by calling :php:meth:`~Controller::render()` directly. Once you have called :php:meth:`~Controller::render()`, CakePHP will not try to re-render the view:

class PostsController extends AppController {
    public function my_action() {
        $this->render('custom_file');
    }
}

This would render app/View/Posts/custom_file.ctp instead of app/View/Posts/my_action.ctp

You can also render views inside plugins using the following syntax: $this->render('PluginName.PluginController/custom_file'). For example:

class PostsController extends AppController {
    public function my_action() {
        $this->render('Users.UserDetails/custom_file');
    }
}

This would render app/Plugin/Users/View/UserDetails/custom_file.ctp

Flow Control

Callbacks

In addition to the :ref:`controller-life-cycle`, CakePHP also supports callbacks related to scaffolding.

Other Useful Methods

Controller Attributes

For a complete list of controller attributes and their descriptions visit the CakePHP API.

$components, $helpers and $uses

The next most often used controller attributes tell CakePHP what :php:attr:`~Controller::$helpers`, :php:attr:`~Controller::$components`, and models you'll be using in conjunction with the current controller. Using these attributes make MVC classes given by :php:attr:`~Controller::$components` and :php:attr:`~Controller::$uses` available to the controller as class variables ($this->ModelName, for example) and those given by :php:attr:`~Controller::$helpers` to the view as an object reference variable ($this->{$helpername}).

Note

Each controller has some of these classes available by default, so you may not need to configure your controller at all.

Other Attributes

While you can check out the details for all controller attributes in the API, there are other controller attributes that merit their own sections in the manual.

More on controllers