Table of Contents : Le Manuel

Introduction

A controller is used to manage the logic for a part of your application. Most commonly, controllers are used to manage the logic for a single model. For example, if you were building a site for an online bakery, you might have a RecipesController and a IngredientsController managing your recipes and their ingredients. In CakePHP, controllers are named after the model they handle, in plural form.

The Recipe model is handled by the RecipesController, the Product model is handled by the ProductsController, and so on.

Your application's controllers are classes that extend the CakePHP AppController class, which in turn extends a core Controller class. The AppController class can be defined in /app/app_controller.php and it should contain methods that are shared between all of your application’s controllers. It extends the Controller class which is a standard CakePHP library.

Controllers can include any number of methods which are usually referred to as actions. Actions are controller methods used to display views. An action is a single method of a controller. CakePHP’s dispatcher calls actions when an incoming request matches a URL to a controller’s action. Returning to our online bakery example, our RecipesController might contain the view(), share(), and search() actions. The controller would be found in /app/controllers/recipes_controller.php and contain:

    <?php
    
    # /app/controllers/recipes_controller.php

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

        function share($customer_id, $recipe_id) {
            //action logic goes here..
        }

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

    ?>
  1. <?php
  2. # /app/controllers/recipes_controller.php
  3. class RecipesController extends AppController {
  4. function view($id) {
  5. //action logic goes here..
  6. }
  7. function share($customer_id, $recipe_id) {
  8. //action logic goes here..
  9. }
  10. function search($query) {
  11. //action logic goes here..
  12. }
  13. }
  14. ?>

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.