Class Controller

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 a controller that are not inherited from 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->getRequest(). The request object contains all the POST, GET and FILES that were part of the request.

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

Controllers are created by ActionDispatcher 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() or RouterBuilder::connect().

Life cycle callbacks

CakePHP fires a number of life cycle callbacks during each request. By implementing a method you can receive the related events. The available callbacks are:

  • beforeFilter(EventInterface $event) Called before each action. This is a good place to do general logic that applies to all actions.
  • beforeRender(EventInterface $event) Called before the view is rendered.
  • beforeRedirect(EventInterface $event, $url, Response $response) Called before a redirect is done.
  • afterFilter(EventInterface $event) Called after each action is complete and after the view is rendered.
Namespace: Cake\Controller

Properties summary

  • $Flash public
    \Cake\Controller\Component\FlashComponent
  • \Cake\Controller\Component\FormProtectionComponent
  • $Paginator public
    \Cake\Controller\Component\PaginatorComponent
  • \Cake\Controller\Component\RequestHandlerComponent
  • $_components protected
    \Cake\Controller\ComponentRegistry

    Instance of ComponentRegistry used to create Components

  • $_eventClass protected
    string

    Default class name for new event objects.

  • $_eventManager protected
    \Cake\Event\EventManagerInterface

    Instance of the Cake\Event\EventManager this object is using to dispatch inner events.

  • $_modelFactories protected
    array

    A list of overridden model factory functions.

  • $_modelType protected
    string

    The model type to use.

  • $_responseClass protected
    string

    The class name to use for creating the response object.

  • $_tableLocator protected
    \Cake\ORM\Locator\LocatorInterface|null

    Table locator instance

  • $_viewBuilder protected
    \Cake\View\ViewBuilder|null

    The view builder instance being used.

  • $autoRender protected
    bool

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

  • $modelClass protected
    string|null

    This object's primary model class name. Should be a plural form.

  • $name protected
    string

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

  • $paginate public
    array

    Settings for pagination.

  • $plugin protected
    string|null

    Automatically set to the name of a plugin.

  • $request protected
    \Cake\Http\ServerRequest

    An instance of a \Cake\Http\ServerRequest object that contains information about the current request.

  • $response protected
    \Cake\Http\Response

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

Method Summary

  • __construct() public

    Constructor.

  • __get() public

    Magic accessor for model autoloading.

  • __set() public

    Magic setter for removed properties.

  • _setModelClass() protected

    Set the modelClass property based on conventions.

  • _templatePath() protected

    Get the templatePath based on controller name and request prefix.

  • afterFilter() public

    Called after the controller action is run and rendered.

  • beforeFilter() public

    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.

  • beforeRedirect() public

    The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.

  • beforeRender() public

    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.

  • components() public

    Get the component registry for this controller.

  • createView() public

    Constructs the view class instance based on the current configuration.

  • disableAutoRender() public

    Disable automatic action rendering.

  • dispatchEvent() public

    Wrapper for creating and dispatching events.

  • enableAutoRender() public

    Enable automatic action rendering.

  • getAction() public

    Get the closure for action to be invoked by ControllerFactory.

  • getEventManager() public

    Returns the Cake\Event\EventManager manager instance for this object.

  • getModelType() public

    Get the model type to be used by this class

  • getName() public

    Returns the controller name.

  • getPlugin() public

    Returns the plugin name.

  • getRequest() public

    Gets the request instance.

  • getResponse() public

    Gets the response instance.

  • getTableLocator() public

    Gets the table locator.

  • implementedEvents() public

    Returns a list of all events that will fire in the controller during its lifecycle.

  • initialize() public

    Initialization hook method.

  • invokeAction() public

    Dispatches the controller action.

  • isAction() public

    Method to check that an action is accessible from a URL.

  • isAutoRenderEnabled() public

    Returns true if an action should be rendered automatically.

  • loadComponent() public

    Add a component to the controller's registry.

  • loadModel() public

    Loads and constructs repository objects required by this object

  • log() public

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

  • modelFactory() public

    Override a existing callable to generate repositories of a given type.

  • paginate() public

    Handles pagination of records in Table objects.

  • redirect() public

    Redirects to given $url, after turning off $this->autoRender.

  • referer() public

    Returns the referring URL for this request.

  • render() public

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

  • set() public

    Saves a variable or an associative array of variables for use inside a template.

  • setAction() public

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

  • setEventManager() public

    Returns the Cake\Event\EventManagerInterface instance for this object.

  • setModelType() public

    Set the model type to be used by this class

  • setName() public

    Sets the controller name.

  • setPlugin() public

    Sets the plugin name.

  • setRequest() public

    Sets the request objects and configures a number of controller properties based on the contents of the request. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are:

  • setResponse() public

    Sets the response instance.

  • setTableLocator() public

    Sets the table locator.

  • shutdownProcess() public

    Perform the various shutdown processes for this controller.

  • startupProcess() public

    Perform the startup process for this controller.

  • viewBuilder() public

    Get the view builder being used.

Method Detail

__construct() public

__construct(?\Cake\Http\ServerRequest $request, ?\Cake\Http\Response $response, ?string $name, ?\Cake\Event\EventManagerInterface $eventManager, ?\Cake\Controller\ComponentRegistry $components)

Constructor.

Sets a number of properties based on conventions if they are empty. To override the conventions CakePHP uses you can define properties in your class declaration.

Parameters

\Cake\Http\ServerRequest|null $request optional

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

\Cake\Http\Response|null $response optional

Response object for this controller.

string|null $name optional

Override the name useful in testing when using mocks.

\Cake\Event\EventManagerInterface|null $eventManager optional

The event manager. Defaults to a new instance.

\Cake\Controller\ComponentRegistry|null $components optional

The component registry. Defaults to a new instance.

__get() public

__get(string $name)

Magic accessor for model autoloading.

Parameters

string $name

Property name

Returns

\Cake\Datasource\RepositoryInterface|null

The model instance or null

__set() public

__set(string $name, mixed $value)

Magic setter for removed properties.

Parameters

string $name

Property name.

mixed $value

Value to set.

_setModelClass() protected

_setModelClass(string $name)

Set the modelClass property based on conventions.

If the property is already set it will not be overwritten

Parameters

string $name

Class name.

_templatePath() protected

_templatePath()

Get the templatePath based on controller name and request prefix.

Returns

string

afterFilter() public

afterFilter(\Cake\Event\EventInterface $event)

Called after the controller action is run and rendered.

Parameters

\Cake\Event\EventInterface $event

An Event instance

Returns

\Cake\Http\Response|null|void

Links

beforeFilter() public

beforeFilter(\Cake\Event\EventInterface $event)

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.

Parameters

\Cake\Event\EventInterface $event

An Event instance

Returns

\Cake\Http\Response|null|void

Links

beforeRedirect() public

beforeRedirect(\Cake\Event\EventInterface $event, mixed $url, \Cake\Http\Response $response)

The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.

If the event is stopped the controller will not continue on to redirect the request. The $url and $status variables have same meaning as for the controller's method. You can set the event result to response instance or modify the redirect location using controller's response instance.

Parameters

\Cake\Event\EventInterface $event

An Event instance

string|array $url

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

\Cake\Http\Response $response

The response object.

Returns

\Cake\Http\Response|null|void

Links

beforeRender() public

beforeRender(\Cake\Event\EventInterface $event)

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.

Parameters

\Cake\Event\EventInterface $event

An Event instance

Returns

\Cake\Http\Response|null|void

Links

components() public

components(?\Cake\Controller\ComponentRegistry $components)

Get the component registry for this controller.

If called with the first parameter, it will be set as the controller $this->_components property

Parameters

\Cake\Controller\ComponentRegistry|null $components optional

Component registry.

Returns

\Cake\Controller\ComponentRegistry

createView() public

createView(?string $viewClass)

Constructs the view class instance based on the current configuration.

Parameters

string|null $viewClass optional

Optional namespaced class name of the View class to instantiate.

Returns

\Cake\View\View

Throws

Cake\View\Exception\MissingViewException
If view class was not found.

disableAutoRender() public

disableAutoRender()

Disable automatic action rendering.

Returns

$this

dispatchEvent() public

dispatchEvent(string $name, ?array $data, ?object $subject)

Wrapper for creating and dispatching events.

Returns a dispatched event.

Parameters

string $name

Name of the event.

array|null $data optional

Any value you wish to be transported with this event to it can be read by listeners.

object|null $subject optional

The object that this event applies to ($this by default).

Returns

\Cake\Event\EventInterface

enableAutoRender() public

enableAutoRender()

Enable automatic action rendering.

Returns

$this

getAction() public

getAction()

Get the closure for action to be invoked by ControllerFactory.

Returns

\Closure

Throws

Cake\Controller\Exception\MissingActionException

getEventManager() public

getEventManager()

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Returns

\Cake\Event\EventManagerInterface

getModelType() public

getModelType()

Get the model type to be used by this class

Returns

string

getName() public

getName()

Returns the controller name.

Returns

string

getPlugin() public

getPlugin()

Returns the plugin name.

Returns

string|null

getRequest() public

getRequest()

Gets the request instance.

Returns

\Cake\Http\ServerRequest

getResponse() public

getResponse()

Gets the response instance.

Returns

\Cake\Http\Response

getTableLocator() public

getTableLocator()

Gets the table locator.

Returns

\Cake\ORM\Locator\LocatorInterface

implementedEvents() public

implementedEvents()

Returns a list of all events that will fire in the controller during its lifecycle.

You can override this function to add your own listener callbacks

Returns

array

initialize() public

initialize()

Initialization hook method.

Implement this method to avoid having to overwrite the constructor and call parent.

invokeAction() public

invokeAction(\Closure $action, array $args)

Dispatches the controller action.

Parameters

\Closure $action

The action closure.

array $args

The arguments to be passed when invoking action.

Throws

UnexpectedValueException
If return value of action is not `null` or `ResponseInterface` instance.

isAction() public

isAction(string $action)

Method to check that an action is accessible from a URL.

Override this method to change which controller methods can be reached. The default implementation disallows access to all methods defined on Cake\Controller\Controller, and allows all public methods on all subclasses of this class.

Parameters

string $action

The action to check.

Returns

bool

Whether or not the method is accessible from a URL.

Throws

ReflectionException

isAutoRenderEnabled() public

isAutoRenderEnabled()

Returns true if an action should be rendered automatically.

Returns

bool

loadComponent() public

loadComponent(string $name, array $config)

Add a component to the controller's registry.

This method will also set the component to a property. For example:

$this->loadComponent('Acl.Acl');

Will result in a Toolbar property being set.

Parameters

string $name

The name of the component to load.

array $config optional

The config for the component.

Returns

\Cake\Controller\Component

Throws

Exception

loadModel() public

loadModel(?string $modelClass, ?string $modelType)

Loads and constructs repository objects required by this object

Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.

If a repository provider does not return an object a MissingModelException will be thrown.

Parameters

string|null $modelClass optional

Name of model class to load. Defaults to $this->modelClass. The name can be an alias like 'Post' or FQCN like App\Model\Table\PostsTable::class.

string|null $modelType optional

The type of repository to load. Defaults to the getModelType() value.

Returns

\Cake\Datasource\RepositoryInterface

The model instance created.

Throws

Cake\Datasource\Exception\MissingModelException
If the model class cannot be found.
UnexpectedValueException
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty.

log() public

log(string $message, mixed $level, mixed $context)

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

Parameters

string $message

Log message.

int|string $level optional

Error level.

string|array $context optional

Additional log data relevant to this message.

Returns

bool

Success of log write.

modelFactory() public

modelFactory(string $type, callable $factory)

Override a existing callable to generate repositories of a given type.

Parameters

string $type

The name of the repository type the factory function is for.

callable $factory

The factory function used to create instances.

paginate() public

paginate(mixed $object, array $settings)

Handles pagination of records in Table objects.

Will load the referenced Table object, and have the PaginatorComponent paginate the query using the request date and settings defined in $this->paginate.

This method will also make the PaginatorHelper available in the view.

Parameters

\Cake\ORM\Table|string|\Cake\ORM\Query|null $object optional

Table to paginate (e.g: Table instance, 'TableName' or a Query object)

array $settings optional

The settings/configuration used for pagination.

Returns

\Cake\ORM\ResultSet|\Cake\Datasource\ResultSetInterface

Query results

Throws

RuntimeException
When no compatible table object can be found.

Links

redirect() public

redirect(mixed $url, int $status)

Redirects to given $url, after turning off $this->autoRender.

Parameters

string|array|\Psr\Http\Message\UriInterface $url

A string, array-based URL or UriInterface instance.

int $status optional

HTTP status code. Defaults to 302.

Returns

\Cake\Http\Response|null

Links

referer() public

referer(mixed $default, bool $local)

Returns the referring URL for this request.

Parameters

string|array|null $default optional

Default URL to use if HTTP_REFERER cannot be read from headers

bool $local optional

If false, do not restrict referring URLs to local server. Careful with trusting external sources.

Returns

string

Referring URL

render() public

render(?string $template, ?string $layout)

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

Parameters

string|null $template optional

Template to use for rendering

string|null $layout optional

Layout to use

Returns

\Cake\Http\Response

A response object containing the rendered view.

Links

set() public

set(mixed $name, mixed $value)

Saves a variable or an associative array of variables for use inside a template.

Parameters

string|array $name

A string or an array of data.

mixed $value optional

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

Returns

$this

setAction() public

setAction(string $action, mixed ...$args)

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

The new action to be 'redirected' to. Any other parameters passed to this method will be passed as parameters to the new action.

mixed ...$args

Arguments passed to the action

Returns

mixed

Returns the return value of the called action

setEventManager() public

setEventManager(\Cake\Event\EventManagerInterface $eventManager)

Returns the Cake\Event\EventManagerInterface instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters

\Cake\Event\EventManagerInterface $eventManager

the eventManager to set

Returns

$this

setModelType() public

setModelType(string $modelType)

Set the model type to be used by this class

Parameters

string $modelType

The model type

Returns

$this

setName() public

setName(string $name)

Sets the controller name.

Parameters

string $name

Controller name.

Returns

$this

setPlugin() public

setPlugin(?string $name)

Sets the plugin name.

Parameters

string|null $name

Plugin name.

Returns

$this

setRequest() public

setRequest(\Cake\Http\ServerRequest $request)

Sets the request objects and configures a number of controller properties based on the contents of the request. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are:

  • $this->request - To the $request parameter

Parameters

\Cake\Http\ServerRequest $request

Request instance.

Returns

$this

setResponse() public

setResponse(\Cake\Http\Response $response)

Sets the response instance.

Parameters

\Cake\Http\Response $response

Response instance.

Returns

$this

setTableLocator() public

setTableLocator(\Cake\ORM\Locator\LocatorInterface $tableLocator)

Sets the table locator.

Parameters

\Cake\ORM\Locator\LocatorInterface $tableLocator

LocatorInterface instance.

Returns

$this

shutdownProcess() public

shutdownProcess()

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.

Returns

\Psr\Http\Message\ResponseInterface|null

startupProcess() public

startupProcess()

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.

Returns

\Psr\Http\Message\ResponseInterface|null

viewBuilder() public

viewBuilder()

Get the view builder being used.

Returns

\Cake\View\ViewBuilder

Property Detail

$Flash public

Type

\Cake\Controller\Component\FlashComponent

$FormProtection public

Type

\Cake\Controller\Component\FormProtectionComponent

$Paginator public

Type

\Cake\Controller\Component\PaginatorComponent

$RequestHandler public

Type

\Cake\Controller\Component\RequestHandlerComponent

$_components protected

Instance of ComponentRegistry used to create Components

Type

\Cake\Controller\ComponentRegistry

$_eventClass protected

Default class name for new event objects.

Type

string

$_eventManager protected

Instance of the Cake\Event\EventManager this object is using to dispatch inner events.

Type

\Cake\Event\EventManagerInterface

$_modelFactories protected

A list of overridden model factory functions.

Type

array

$_modelType protected

The model type to use.

Type

string

$_responseClass protected

The class name to use for creating the response object.

Type

string

$_tableLocator protected

Table locator instance

Type

\Cake\ORM\Locator\LocatorInterface|null

$_viewBuilder protected

The view builder instance being used.

Type

\Cake\View\ViewBuilder|null

$autoRender protected

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

Type

bool

$modelClass protected

This object's primary model class name. Should be a plural form.

CakePHP will not inflect the name.

Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use Plugin.Comments style names to correctly load models from the correct plugin.

Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.

Type

string|null

$name protected

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

Set automatically using conventions in Controller::__construct().

Type

string

$paginate public

Settings for pagination.

Used to pre-configure pagination preferences for the various tables your controller will be paginating.

Type

array

$plugin protected

Automatically set to the name of a plugin.

Type

string|null

$request protected

An instance of a \Cake\Http\ServerRequest 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.

Type

\Cake\Http\ServerRequest

$response protected

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

Type

\Cake\Http\Response

© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.0/class-Cake.Controller.Controller.html