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.
Properties summary
- $Flash public
\Cake\Controller\Component\FlashComponent - $FormProtection public
\Cake\Controller\Component\FormProtectionComponent - $Paginator public
\Cake\Controller\Component\PaginatorComponent - $RequestHandler public
\Cake\Controller\Component\RequestHandlerComponent - $_components protected
\Cake\Controller\ComponentRegistryInstance of ComponentRegistry used to create Components
- $_eventClass protected
stringDefault class name for new event objects.
- $_eventManager protected
\Cake\Event\EventManagerInterfaceInstance of the Cake\Event\EventManager this object is using to dispatch inner events.
- $_modelFactories protected
arrayA list of overridden model factory functions.
- $_modelType protected
stringThe model type to use.
- $_responseClass protected
stringThe class name to use for creating the response object.
- $_tableLocator protected
\Cake\ORM\Locator\LocatorInterface|nullTable locator instance
- $_viewBuilder protected
\Cake\View\ViewBuilder|nullThe view builder instance being used.
- $autoRender protected
boolSet to true to automatically render the view after action logic.
- $modelClass protected
string|nullThis object's primary model class name. Should be a plural form.
- $name protected
stringThe name of this controller. Controller names are plural, named after the model they manipulate.
- $paginate public
arraySettings for pagination.
- $plugin protected
string|nullAutomatically set to the name of a plugin.
- $request protected
\Cake\Http\ServerRequestAn instance of a \Cake\Http\ServerRequest object that contains information about the current request.
- $response protected
\Cake\Http\ResponseAn instance of a Response object that contains information about the impending response
Method Summary
- 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.
- implementedEvents() public
Returns a list of all events that will fire in the controller during its lifecycle.
- log() public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
- render() public
Instantiates the correct view class, hands it its data, and uses it to render the view output.
- setAction() public
Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
- 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:
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|nullThe 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
stringafterFilter() 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|voidLinks
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|voidLinks
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|voidLinks
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|voidLinks
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\ComponentRegistrycreateView() 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\ViewThrows
Cake\View\Exception\MissingViewExceptionIf view class was not found.
disableAutoRender() public
disableAutoRender()
Disable automatic action rendering.
Returns
$thisdispatchEvent() 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\EventInterfaceenableAutoRender() public
enableAutoRender()
Enable automatic action rendering.
Returns
$thisgetAction() public
getAction()
Get the closure for action to be invoked by ControllerFactory.
Returns
\ClosureThrows
Cake\Controller\Exception\MissingActionExceptiongetEventManager() 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\EventManagerInterfacegetModelType() public
getModelType()
Get the model type to be used by this class
Returns
stringgetName() public
getName()
Returns the controller name.
Returns
stringgetPlugin() public
getPlugin()
Returns the plugin name.
Returns
string|nullgetRequest() public
getRequest()
Gets the request instance.
Returns
\Cake\Http\ServerRequestgetResponse() public
getResponse()
Gets the response instance.
Returns
\Cake\Http\ResponsegetTableLocator() public
getTableLocator()
Gets the table locator.
Returns
\Cake\ORM\Locator\LocatorInterfaceimplementedEvents() 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
arrayinitialize() 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
UnexpectedValueExceptionIf 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
boolWhether or not the method is accessible from a URL.
Throws
ReflectionExceptionisAutoRenderEnabled() public
isAutoRenderEnabled()
Returns true if an action should be rendered automatically.
Returns
boolloadComponent() 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\ComponentThrows
ExceptionloadModel() 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 likeApp\Model\Table\PostsTable::class.-
string|null$modelType optional The type of repository to load. Defaults to the getModelType() value.
Returns
\Cake\Datasource\RepositoryInterfaceThe model instance created.
Throws
Cake\Datasource\Exception\MissingModelExceptionIf the model class cannot be found.
UnexpectedValueExceptionIf $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
boolSuccess 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\ResultSetInterfaceQuery results
Throws
RuntimeExceptionWhen 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|nullLinks
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
stringReferring 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\ResponseA 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
$thissetAction() 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
mixedReturns 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
$thissetModelType() public
setModelType(string $modelType)
Set the model type to be used by this class
Parameters
-
string$modelType The model type
Returns
$thissetName() public
setName(string $name)
Sets the controller name.
Parameters
-
string$name Controller name.
Returns
$thissetPlugin() public
setPlugin(?string $name)
Sets the plugin name.
Parameters
-
string|null$name Plugin name.
Returns
$thissetRequest() 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
$thissetResponse() public
setResponse(\Cake\Http\Response $response)
Sets the response instance.
Parameters
-
\Cake\Http\Response$response Response instance.
Returns
$thissetTableLocator() public
setTableLocator(\Cake\ORM\Locator\LocatorInterface $tableLocator)
Sets the table locator.
Parameters
-
\Cake\ORM\Locator\LocatorInterface$tableLocator LocatorInterface instance.
Returns
$thisshutdownProcess() public
shutdownProcess()
Perform the various shutdown processes for this controller.
Fire the Components and Controller callbacks in the correct order.
- triggers the component
shutdowncallback. - calls the Controller's
afterFiltermethod.
Returns
\Psr\Http\Message\ResponseInterface|nullstartupProcess() public
startupProcess()
Perform the startup process for this controller.
Fire the Components and Controller callbacks in the correct order.
- Initializes components, which fires their
initializecallback - Calls the controller
beforeFilter. - triggers Component
startupmethods.
Returns
\Psr\Http\Message\ResponseInterface|nullviewBuilder() public
viewBuilder()
Get the view builder being used.
Returns
\Cake\View\ViewBuilderProperty 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