Controller Class Info:

Class Declaration:

class Controller extends Object implements CakeEventListener

File name:
Cake/Controller/Controller.php
Description:

Application controller class for organization of business logic. Provides basic functionality, such as rendering views inside layouts, automatic model availability, redirection, callbacks, and more.

Controllers should provide a number of 'action' methods. These are public methods on the controller that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for performing a specific action on a resource or collection of resources. For example adding or editing a new object, or listing a set of objects.

You can access request parameters, using $this->request. The request object contains all the POST, GET and FILES that were part of the request.

After performing the required actions, controllers are responsible for creating a response. This usually takes the form of a generated View, or possibly a redirection to another controller action. In either case $this->response allows you to manipulate all aspects of the response.

Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions use conventional names. For example /posts/index maps to PostsController::index(). You can re-map urls using Router::connect().

Class Inheritance

Object

Interfaces Implemented
CakeEventListener
Package
Cake.Controller
Property

AclComponent $Acl

AuthComponent $Auth

CookieComponent $Cookie

EmailComponent $Email

PaginatorComponent $Paginator

RequestHandlerComponent $RequestHandler

SecurityComponent $Security

SessionComponent $Session

Link
http://book.cakephp.org/2.0/en/controllers.html

Properties:

  • autoLayout boolean

    Set to true to automatically render the layout around views.

  • autoRender boolean

    Set to true to automatically render the view after action logic.

  • cacheAction mixed

    Used to define methods a controller that will be cached. To cache a single action, the value is set to an array containing keys that match action names and values that denote cache expiration times (in seconds).

    Example:

    public $cacheAction = array(
            'view/23/' => 21600,
            'recalled/' => 86400
        );

    $cacheAction can also be set to a strtotime() compatible string. This marks all the actions in the controller for view caching.

  • components array

    Array containing the names of components this controller uses. Component names should not contain the "Component" portion of the classname.

    Example: public $components = array('Session', 'RequestHandler', 'Acl');

  • Components ComponentCollection

    Instance of ComponentCollection used to handle callbacks.

  • _eventManager CakeEventManager

    Instance of the CakeEventManager this controller is using to dispatch inner events.

  • ext string

    File extension for view templates. Defaults to Cake's conventional ".ctp".

  • helpers mixed A single name as a string or a list of names as an array.

    An array containing the names of helpers this controller uses. The array elements should not contain the "Helper" part of the classname.

    Example: public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');

  • layout string

    The name of the layout file to render the view inside of. The name specified is the filename of the layout in /app/View/Layouts without the .ctp extension.

  • layoutPath string

    The name of the layouts subfolder containing layouts for this controller.

  • _mergeParent string

    The class name of the parent class you wish to merge with. Typically this is AppController, but you may wish to merge vars with a different parent class.

  • methods array

    Holds current methods of the controller. This is a list of all the methods reachable via url. Modifying this array, will allow you to change which methods can be reached.

  • modelClass string

    This controller's primary model class name, the Inflector::singularize()'ed version of the controller's $name property.

    Example: For a controller named 'Comments', the modelClass would be 'Comment'

  • modelKey string

    This controller's model key name, an underscored version of the controller's $modelClass property.

    Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment'

  • name string

    The name of this controller. Controller names are plural, named after the model they manipulate.

  • passedArgs mixed

    Holds all params passed and named.

  • plugin string

    Automatically set to the name of a plugin.

  • request CakeRequest

    An instance of a CakeRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.

  • response CakeResponse

    An instance of a CakeResponse object that contains information about the impending response

  • _responseClass string

    The classname to use for creating the response object.

  • scaffold mixed

    Triggers Scaffolding

  • uses mixed A single name as a string or a list of names as an array.

    An array containing the class names of models this controller uses.

    Example: public $uses = array('Product', 'Post', 'Comment');

    Can be set to several values to express different options:

    • true Use the default inflected model name.
    • array() Use only models defined in the parent class.
    • false Use no models at all, do not merge with parent class either.
    • array('Post', 'Comment') Use only the Post and Comment models. Models Will also be merged with the parent class.

    The default value is true.

  • validationErrors array Validation errors, or false if none

    Holds any validation errors produced by the last call of the validateErrors() method/

  • View View

    Instance of the View created during rendering. Won't be set until after Controller::render() is called.

  • view string

    The name of the view file to render. The name specified is the filename in /app/View/<SubFolder> without the .ctp extension.

  • viewClass string

    The name of the View class this controller sends output to.

  • viewPath string

    The name of the views subfolder containing views for this controller.

  • viewVars array

    Contains variables to be handed to the view.

Method Summary:

Show/Hide parent methods

afterFilter

top

Called after the controller action is run and rendered.

Method defined in:
Cake/Controller/Controller.php on line 1133

afterScaffoldSave

top

This method should be overridden in child classes.

Parameters:
  • string $method required

    name of method called either edit or update.

Method defined in:
Cake/Controller/Controller.php on line 1166

_afterScaffoldSave

top

Alias to afterScaffoldSave()

Parameters:
  • string $method required

Method defined in:
Cake/Controller/Controller.php on line 1178
Return

boolean

See

Controller::afterScaffoldSave()

Deprecated

_afterScaffoldSaveError

top

Alias to afterScaffoldSaveError()

Parameters:
  • string $method required

Method defined in:
Cake/Controller/Controller.php on line 1201
Return

boolean

See

Controller::afterScaffoldSaveError()

Deprecated

afterScaffoldSaveError

top

This method should be overridden in child classes.

Parameters:
  • string $method required

    name of method called either edit or update.

Method defined in:
Cake/Controller/Controller.php on line 1189

beforeFilter

top

Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action.

Method defined in:
Cake/Controller/Controller.php on line 1094

beforeRedirect

top

The beforeRedirect method is invoked when the controller's redirect method is called but before any further action. If this method returns false the controller will not continue on to redirect the request. The $url, $status and $exit variables have same meaning as for the controller's method. You can also return a string which will be interpreted as the url to redirect to or return associative array with key 'url' and optionally 'status' and 'exit'.

Parameters:
  • mixed $url required

    A string or array-based URL pointing to another location within the app, or an absolute URL

  • integer $status optional NULL

    Optional HTTP status code (eg: 404)

  • boolean $exit optional true

    If true, exit() will be called after the redirect

Method defined in:
Cake/Controller/Controller.php on line 1124
Return

mixed false to stop redirection event, string controllers a new redirection url or array with the keys url, status and exit to be used by the redirect method.

Link
http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks

beforeRender

top

Called after the controller action is run, but before the view is rendered. You can use this method to perform logic or set view variables that are required on every request.

Method defined in:
Cake/Controller/Controller.php on line 1104

beforeScaffold

top

This method should be overridden in child classes.

Parameters:
  • string $method required

    name of method called example index, edit, etc.

Method defined in:
Cake/Controller/Controller.php on line 1143

_beforeScaffold

top

Alias to beforeScaffold()

Parameters:
  • string $method required

Method defined in:
Cake/Controller/Controller.php on line 1155
Return

boolean

See

Controller::beforeScaffold()

Deprecated

__construct

top

Constructor.

Parameters:
  • CakeRequest $request optional NULL

    Request object for this controller. Can be null for testing, but expect that features that use the request parameters will not work.

  • CakeResponse $response optional NULL

    Response object for this controller.

Method defined in:
Cake/Controller/Controller.php on line 317

constructClasses

top

Loads Model classes based on the uses property see Controller::loadModel(); for more info. Loads Components and prepares them for initialization.

Method defined in:
Cake/Controller/Controller.php on line 633
Return

mixed true if models found and instance created.

See

Controller::loadModel()

Link
http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses
Throws

MissingModelException

disableCache

top

Forces the user's browser not to cache the results of the current request.

Method defined in:
Cake/Controller/Controller.php on line 989

dispatchMethod

top

Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array

Parameters:
  • string $method required

    Name of the method to call

  • array $params optional array ( )

    Parameter list to use when calling $method

Method defined in:
Cake/Core/Object.php on line 110
Return

mixed Returns the result of the method call

flash

top

Shows a message to the user for $pause seconds, then redirects to $url. Uses flash.ctp as the default layout for the message. Does not work if the current debug level is higher than 0.

Parameters:
  • string $message required

    Message to display to the user

  • mixed $url required

    Relative string or array-based URL to redirect to after the time expires

  • integer $pause optional 1

    Time to show the message

  • string $layout optional 'flash'

    Layout you want to use, defaults to 'flash'

Method defined in:
Cake/Controller/Controller.php on line 1005

__get

top

Provides backwards compatibility access to the request object properties. Also provides the params alias.

Parameters:
  • string $name required

Method defined in:
Cake/Controller/Controller.php on line 389
Return

void

getEventManager

top

Returns the CakeEventManager manager instance that is handling any callbacks. You can use this instance to register any new listeners or callbacks to the controller events, or create your own events and trigger them at will.

Method defined in:
Cake/Controller/Controller.php on line 650
Return

CakeEventManager

_getScaffold

top

Returns a scaffold object to use for dynamically scaffolded controllers.

Parameters:
  • CakeRequest $request required

Method defined in:
Cake/Controller/Controller.php on line 529
Return

Scaffold

header

top

Convenience and object wrapper method for CakeResponse::header().

Parameters:
  • string $status required

    The header message that is being set.

Method defined in:
Cake/Controller/Controller.php on line 823
Return

void

Deprecated

Use CakeResponse::header()

httpCodes

top

Queries & sets valid HTTP response codes & messages.

httpCodes(404); // returns array(404 => 'Not Found')

   httpCodes(array(
       701 => 'Unicorn Moved',
       800 => 'Unexpected Minotaur'

)); // sets these new values, and returns true

Parameters:
  • mixed $code optional NULL

    If $code is an integer, then the corresponding code/message is returned if it exists, null if it does not exist. If $code is an array, then the 'code' and 'message' keys of each nested array are added to the default HTTP codes. Example:

Method defined in:
Cake/Controller/Controller.php on line 706
Return

mixed Associative array of the HTTP codes as keys, and the message strings as values, or null of the given $code does not exist.

Deprecated

Use CakeResponse::httpCodes();

implementedEvents

top

Returns a list of all events that will fire in the controller during it's lifecycle. You can override this function to add you own listener callbacks

Method defined in:
Cake/Controller/Controller.php on line 614
Return

array

invokeAction

top

Dispatches the controller action. Checks that the action exists and isn't private.

Parameters:
  • CakeRequest $request required

Method defined in:
Cake/Controller/Controller.php on line 475
Return

mixed The resulting response.

Throws

PrivateActionException When actions are not public or prefixed by _

MissingActionException When actions are not defined and scaffolding is not enabled.

_isPrivateAction

top

Check if the request's action is marked as private, with an underscore, or if the request is attempting to directly accessing a prefixed action.

Parameters:
  • ReflectionMethod $method required

    The method to be invoked.

  • CakeRequest $request required

    The request to check.

Method defined in:
Cake/Controller/Controller.php on line 506
Return

boolean

__isset

top

Provides backwards compatibility to avoid problems with empty and isset to alias properties. Lazy loads models using the loadModel() method if declared in $uses

Parameters:
  • string $name required

Method defined in:
Cake/Controller/Controller.php on line 351
Return

void

loadModel

top

Loads and instantiates models required by this controller. If the model is non existent, it will throw a missing database table error, as Cake generates dynamic models for the time being.

Parameters:
  • string $modelClass optional NULL

    Name of model class to load

  • mixed $id optional NULL

    Initial ID the instanced model class should have

Method defined in:
Cake/Controller/Controller.php on line 720
Return

mixed true when single model found and instance created, error returned if model not found.

Throws

MissingModelException if the model class cannot be found.

log

top

Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.

Parameters:
  • string $msg required

    Log message

  • integer $type optional 2

    Error type constant. Defined in app/Config/core.php.

Method defined in:
Cake/Core/Object.php on line 149
Return

boolean Success of log write

_mergeControllerVars

top

Merge components, helpers, and uses vars from Controller::$_mergeParent and PluginAppController.

Method defined in:
Cake/Controller/Controller.php on line 539
Return

void

_mergeUses

top

Helper method for merging the $uses property together.

Merges the elements not already in $this->uses into $this->uses.

Parameters:
  • mixed $merge required

    The data to merge in.

Method defined in:
Cake/Controller/Controller.php on line 595
Return

void

_mergeVars

top

Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'

This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.

Parameters:
  • array $properties required

    The name of the properties to merge.

  • string $class required

    The class to merge the property with.

  • boolean $normalize optional true

    Set to true to run the properties through Set::normalize() before merging.

Method defined in:
Cake/Core/Object.php on line 187
Return

void

paginate

top

Handles automatic pagination of model records.

Parameters:
  • mixed $object optional NULL

    Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel')

  • mixed $scope optional array ( )

    Conditions to use while paginating

  • array $whitelist optional array ( )

    List of allowed options for paging

Method defined in:
Cake/Controller/Controller.php on line 1083
Return

array Model query results

Link
http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate
Deprecated

Use PaginatorComponent instead

_parseBeforeRedirect

top

Parse beforeRedirect Response

Parameters:
  • mixed $response required

    Response from beforeRedirect callback

  • mixed $url required

    The same value of beforeRedirect

  • integer $status required

    The same value of beforeRedirect

  • boolean $exit required

    The same value of beforeRedirect

Method defined in:
Cake/Controller/Controller.php on line 803
Return

array Array with keys url, status and exit

postConditions

top

Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.

Parameters:
  • array $data optional array ( )

    POST'ed data organized by model and field

  • mixed $op optional NULL

    A string containing an SQL comparison operator, or an array matching operators to fields

  • string $bool optional 'AND'

    SQL boolean operator: AND, OR, XOR, etc.

  • boolean $exclusive optional false

    If true, and $op is an array, fields not included in $op will not be included in the returned conditions

Method defined in:
Cake/Controller/Controller.php on line 1026
Return

array An array of model conditions

Deprecated

redirect

top

Redirects to given $url, after turning off $this->autoRender. Script execution is halted after the redirect.

Parameters:
  • mixed $url required

    A string or array-based URL pointing to another location within the app, or an absolute URL

  • integer $status optional NULL

    Optional HTTP status code (eg: 404)

  • boolean $exit optional true

    If true, exit() will be called after the redirect

Method defined in:
Cake/Controller/Controller.php on line 752
Return

mixed void if $exit = false. Terminates script if $exit = true

Link
http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect

referer

top

Returns the referring URL for this request.

Parameters:
  • string $default optional NULL

    Default URL to use if HTTP_REFERER cannot be read from headers

  • boolean $local optional false

    If true, restrict referring URLs to local server

Method defined in:
Cake/Controller/Controller.php on line 971

render

top

Instantiates the correct view class, hands it its data, and uses it to render the view output.

Parameters:
  • string $view optional NULL

    View to use for rendering

  • string $layout optional NULL

    Layout to use

Method defined in:
Cake/Controller/Controller.php on line 922
Return

CakeResponse A response object containing the rendered view.

Link
http://book.cakephp.org/2.0/en/controllers.html#Controller::render

requestAction

top

Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()

Passing POST and GET data

POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.

Parameters:
  • mixed $url required

    String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed and named arguments in the $url parameter.

  • array $extra optional array ( )

    if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.

Method defined in:
Cake/Core/Object.php on line 66
Return

mixed Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.

scaffoldError

top

This method should be overridden in child classes. If not it will render a scaffold error. Method MUST return true in child classes

Parameters:
  • string $method required

    name of method called example index, edit, etc.

Method defined in:
Cake/Controller/Controller.php on line 1214

_scaffoldError

top

Alias to scaffoldError()

Parameters:
  • string $method required

Method defined in:
Cake/Controller/Controller.php on line 1226
Return

boolean

See

Controller::scaffoldError()

Deprecated

set

top

Saves a variable for use inside a view template.

Parameters:
  • mixed $one required

    A string or an array of data.

  • mixed $two optional NULL

    Value in case $one is a string (which then works as the key). Unused if $one is an associative array, otherwise serves as the values to $one's keys.

Method defined in:
Cake/Controller/Controller.php on line 836

_set

top

Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.

Parameters:
  • array $properties optional array ( )

    An associative array containing properties and corresponding values.

Method defined in:
Cake/Core/Object.php on line 164
Return

void

__set

top

Provides backwards compatibility access for setting values to the request object.

Parameters:
  • string $name required

  • mixed $value required

Method defined in:
Cake/Controller/Controller.php on line 418
Return

void

setAction

top

Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()

Examples:

setAction('another_action');
setAction('action_with_parameters', $parameter1);

Parameters:
  • string $action required

    The new action to be 'redirected' to

Method defined in:
Cake/Controller/Controller.php on line 864
Return

mixed Returns the return value of the called action

setRequest

top

Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are

  • $this->request - To the $request parameter
  • $this->plugin - To the $request->params['plugin']
  • $this->view - To the $request->params['action']
  • $this->autoLayout - To the false if $request->params['bare']; is set.
  • $this->autoRender - To false if $request->params['return'] == 1
  • $this->passedArgs - The the combined results of params['named'] and params['pass]

Parameters:
  • CakeRequest $request required

Method defined in:
Cake/Controller/Controller.php on line 449
Return

void

shutdownProcess

top

Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order.

  • triggers the component shutdown callback.
  • calls the Controller's afterFilter method.

Method defined in:
Cake/Controller/Controller.php on line 683
Return

void

startupProcess

top

Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order.

  • Initializes components, which fires their initialize callback
  • Calls the controller beforeFilter.
  • triggers Component startup methods.

Method defined in:
Cake/Controller/Controller.php on line 669
Return

void

_stop

top

Stop execution of the current script. Wraps exit() making testing easier.

Parameters:
Method defined in:
Cake/Core/Object.php on line 137
Return

void

toString

top

Object-to-string conversion. Each class can override this method as necessary.

Method defined in:
Cake/Core/Object.php on line 41
Return

string The name of this class

validate

top

Returns number of errors in a submitted FORM.

Method defined in:
Cake/Controller/Controller.php on line 877
Return

integer Number of errors

validateErrors

top

Validates models passed by parameters. Example:

$errors = $this->validateErrors($this->Article, $this->User);

Method defined in:
Cake/Controller/Controller.php on line 895
Return

array Validation errors, or false if none