Controller
in package
implements
EventListenerInterface, EventDispatcherInterface
uses
EventDispatcherTrait, LocatorAwareTrait, LogTrait, ModelAwareTrait, ViewVarsTrait
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 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 RouteBuilder::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.
Tags
Attributes
- #[AllowDynamicProperties]
Table of Contents
Interfaces
- EventListenerInterface
- Objects implementing this interface should declare the `implementedEvents()` method to notify the event manager what methods should be called when an event is triggered.
- EventDispatcherInterface
- Objects implementing this interface can emit events.
Properties
- $Auth : AuthComponent
- $CheckHttpCache : CheckHttpCacheComponent
- $Flash : FlashComponent
- $FormProtection : FormProtectionComponent
- $paginate : array<string|int, mixed>
- Settings for pagination.
- $Paginator : PaginatorComponent
- $RequestHandler : RequestHandlerComponent
- $Security : SecurityComponent
- $_components : ComponentRegistry|null
- Instance of ComponentRegistry used to create Components
- $_eventClass : string
- Default class name for new event objects.
- $_eventManager : EventManagerInterface|null
- Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
- $_modelFactories : array<string|int, callable|LocatorInterface>
- A list of overridden model factory functions.
- $_modelType : string
- The model type to use.
- $_tableLocator : LocatorInterface|null
- Table locator instance
- $_viewBuilder : ViewBuilder|null
- The view builder instance being used.
- $autoRender : bool
- Set to true to automatically render the view after action logic.
- $defaultTable : string|null
- This object's default table alias.
- $middlewares : array<string|int, mixed>
- Middlewares list.
- $modelClass : string|null
- This object's primary model class name. Should be a plural form.
- $name : string
- The name of this controller. Controller names are plural, named after the model they manipulate.
- $plugin : string|null
- Automatically set to the name of a plugin.
- $request : ServerRequest
- An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
- $response : Response
- An instance of a Response object that contains information about the impending response
Methods
- __construct() : mixed
- Constructor.
- __get() : RepositoryInterface|null
- Magic accessor for model autoloading.
- __set() : void
- Magic setter for removed properties.
- afterFilter() : Response|null|void
- Called after the controller action is run and rendered.
- beforeFilter() : Response|null|void
- 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() : Response|null|void
- The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.
- beforeRender() : Response|null|void
- 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() : ComponentRegistry
- Get the component registry for this controller.
- createView() : View
- Constructs the view class instance based on the current configuration.
- disableAutoRender() : $this
- Disable automatic action rendering.
- dispatchEvent() : EventInterface
- Wrapper for creating and dispatching events.
- enableAutoRender() : $this
- Enable automatic action rendering.
- fetchTable() : Table
- Convenience method to get a table instance.
- getAction() : Closure
- Get the closure for action to be invoked by ControllerFactory.
- getEventManager() : EventManagerInterface
- Returns the Cake\Event\EventManager manager instance for this object.
- getMiddleware() : array<string|int, mixed>
- Get middleware to be applied for this controller.
- getModelType() : string
- Get the model type to be used by this class
- getName() : string
- Returns the controller name.
- getPlugin() : string|null
- Returns the plugin name.
- getRequest() : ServerRequest
- Gets the request instance.
- getResponse() : Response
- Gets the response instance.
- getTableLocator() : LocatorInterface
- Gets the table locator.
- implementedEvents() : array<string, mixed>
- Returns a list of all events that will fire in the controller during its lifecycle.
- initialize() : void
- Initialization hook method.
- invokeAction() : void
- Dispatches the controller action.
- isAction() : bool
- Method to check that an action is accessible from a URL.
- isAutoRenderEnabled() : bool
- Returns true if an action should be rendered automatically.
- loadComponent() : Component
- Add a component to the controller's registry.
- loadModel() : RepositoryInterface
- Loads and constructs repository objects required by this object
- log() : bool
- Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
- middleware() : void
- Register middleware for the controller.
- modelFactory() : void
- Override a existing callable to generate repositories of a given type.
- paginate() : ResultSet|ResultSetInterface
- Handles pagination of records in Table objects.
- redirect() : Response|null
- Redirects to given $url, after turning off $this->autoRender.
- referer() : string
- Returns the referring URL for this request.
- render() : Response
- Instantiates the correct view class, hands it its data, and uses it to render the view output.
- set() : $this
- Saves a variable or an associative array of variables for use inside a template.
- setAction() : mixed
- Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
- setEventManager() : $this
- Returns the Cake\Event\EventManagerInterface instance for this object.
- setModelType() : $this
- Set the model type to be used by this class
- setName() : $this
- Sets the controller name.
- setPlugin() : $this
- Sets the plugin name.
- setRequest() : $this
- 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() : $this
- Sets the response instance.
- setTableLocator() : $this
- Sets the table locator.
- shutdownProcess() : ResponseInterface|null
- Perform the various shutdown processes for this controller.
- startupProcess() : ResponseInterface|null
- Perform the startup process for this controller.
- viewBuilder() : ViewBuilder
- Get the view builder being used.
- viewClasses() : array<string|int, string>
- Get the View classes this controller can perform content negotiation with.
- _setModelClass() : void
- Set the modelClass property based on conventions.
- _templatePath() : string
- Get the templatePath based on controller name and request prefix.
- chooseViewClass() : string|null
- Use the view classes defined on this controller to view selection based on content-type negotiation.
Properties
$Auth
public
AuthComponent
$Auth
$CheckHttpCache
public
CheckHttpCacheComponent
$CheckHttpCache
$Flash
public
FlashComponent
$Flash
$FormProtection
public
FormProtectionComponent
$FormProtection
$paginate
Settings for pagination.
public
array<string|int, mixed>
$paginate
= []
Used to pre-configure pagination preferences for the various tables your controller will be paginating.
Tags
$Paginator
public
PaginatorComponent
$Paginator
$RequestHandler
public
RequestHandlerComponent
$RequestHandler
$Security
public
SecurityComponent
$Security
$_components
Instance of ComponentRegistry used to create Components
protected
ComponentRegistry|null
$_components
$_eventClass
Default class name for new event objects.
protected
string
$_eventClass
= \Cake\Event\Event::class
$_eventManager
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
protected
EventManagerInterface|null
$_eventManager
$_modelFactories
A list of overridden model factory functions.
protected
array<string|int, callable|LocatorInterface>
$_modelFactories
= []
$_modelType
The model type to use.
protected
string
$_modelType
= 'Table'
$_tableLocator
Table locator instance
protected
LocatorInterface|null
$_tableLocator
$_viewBuilder
The view builder instance being used.
protected
ViewBuilder|null
$_viewBuilder
$autoRender
Set to true to automatically render the view after action logic.
protected
bool
$autoRender
= true
$defaultTable
This object's default table alias.
protected
string|null
$defaultTable
= null
$middlewares
Middlewares list.
protected
array<string|int, mixed>
$middlewares
= []
Tags
$modelClass
This object's primary model class name. Should be a plural form.
Use Cake\ORM\Locator\LocatorAwareTrait::$defaultTable
instead.
protected
string|null
$modelClass
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.
$name
The name of this controller. Controller names are plural, named after the model they manipulate.
protected
string
$name
Set automatically using conventions in Controller::__construct().
$plugin
Automatically set to the name of a plugin.
protected
string|null
$plugin
$request
An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
protected
ServerRequest
$request
This object contains all the information about a request and several methods for reading additional information about the request.
Tags
$response
An instance of a Response object that contains information about the impending response
protected
Response
$response
Tags
Methods
__construct()
Constructor.
public
__construct([ServerRequest|null $request = null ][, Response|null $response = null ][, string|null $name = null ][, EventManagerInterface|null $eventManager = null ][, ComponentRegistry|null $components = null ]) : mixed
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
- $request : ServerRequest|null = null
-
Request object for this controller. Can be null for testing, but expect that features that use the request parameters will not work.
- $response : Response|null = null
-
Response object for this controller.
- $name : string|null = null
-
Override the name useful in testing when using mocks.
- $eventManager : EventManagerInterface|null = null
-
The event manager. Defaults to a new instance.
- $components : ComponentRegistry|null = null
-
The component registry. Defaults to a new instance.
__get()
Magic accessor for model autoloading.
public
__get(string $name) : RepositoryInterface|null
Parameters
- $name : string
-
Property name
Return values
RepositoryInterface|null —The model instance or null
__set()
Magic setter for removed properties.
public
__set(string $name, mixed $value) : void
Parameters
- $name : string
-
Property name.
- $value : mixed
-
Value to set.
afterFilter()
Called after the controller action is run and rendered.
public
afterFilter(EventInterface $event) : Response|null|void
Parameters
- $event : EventInterface
-
An Event instance
Tags
Return values
Response|null|voidbeforeFilter()
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.
public
beforeFilter(EventInterface $event) : Response|null|void
Parameters
- $event : EventInterface
-
An Event instance
Tags
Return values
Response|null|voidbeforeRedirect()
The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.
public
beforeRedirect(EventInterface $event, array<string|int, mixed>|string $url, Response $response) : Response|null|void
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
- $event : EventInterface
-
An Event instance
- $url : array<string|int, mixed>|string
-
A string or array-based URL pointing to another location within the app, or an absolute URL
- $response : Response
-
The response object.
Tags
Return values
Response|null|voidbeforeRender()
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.
public
beforeRender(EventInterface $event) : Response|null|void
Parameters
- $event : EventInterface
-
An Event instance
Tags
Return values
Response|null|voidcomponents()
Get the component registry for this controller.
public
components([ComponentRegistry|null $components = null ]) : ComponentRegistry
If called with the first parameter, it will be set as the controller $this->_components property
Parameters
- $components : ComponentRegistry|null = null
-
Component registry.
Return values
ComponentRegistrycreateView()
Constructs the view class instance based on the current configuration.
public
createView([string|null $viewClass = null ]) : View
Parameters
- $viewClass : string|null = null
-
Optional namespaced class name of the View class to instantiate.
Tags
Return values
ViewdisableAutoRender()
Disable automatic action rendering.
public
disableAutoRender() : $this
Tags
Return values
$thisdispatchEvent()
Wrapper for creating and dispatching events.
public
dispatchEvent(string $name[, array<string|int, mixed>|null $data = null ][, object|null $subject = null ]) : EventInterface
Returns a dispatched event.
Parameters
- $name : string
-
Name of the event.
- $data : array<string|int, mixed>|null = null
-
Any value you wish to be transported with this event to it can be read by listeners.
- $subject : object|null = null
-
The object that this event applies to ($this by default).
Return values
EventInterfaceenableAutoRender()
Enable automatic action rendering.
public
enableAutoRender() : $this
Tags
Return values
$thisfetchTable()
Convenience method to get a table instance.
public
fetchTable([string|null $alias = null ][, array<string, mixed> $options = [] ]) : Table
Parameters
- $alias : string|null = null
-
The alias name you want to get. Should be in CamelCase format. If
null
then the value of $defaultTable property is used. - $options : array<string, mixed> = []
-
The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
Tags
Return values
TablegetAction()
Get the closure for action to be invoked by ControllerFactory.
public
getAction() : Closure
Tags
Return values
ClosuregetEventManager()
Returns the Cake\Event\EventManager manager instance for this object.
public
getEventManager() : EventManagerInterface
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.
Return values
EventManagerInterfacegetMiddleware()
Get middleware to be applied for this controller.
public
getMiddleware() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed>getModelType()
Get the model type to be used by this class
public
getModelType() : string
Return values
stringgetName()
Returns the controller name.
public
getName() : string
Tags
Return values
stringgetPlugin()
Returns the plugin name.
public
getPlugin() : string|null
Tags
Return values
string|nullgetRequest()
Gets the request instance.
public
getRequest() : ServerRequest
Tags
Return values
ServerRequestgetResponse()
Gets the response instance.
public
getResponse() : Response
Tags
Return values
ResponsegetTableLocator()
Gets the table locator.
public
getTableLocator() : LocatorInterface
Return values
LocatorInterfaceimplementedEvents()
Returns a list of all events that will fire in the controller during its lifecycle.
public
implementedEvents() : array<string, mixed>
You can override this function to add your own listener callbacks
Return values
array<string, mixed>initialize()
Initialization hook method.
public
initialize() : void
Implement this method to avoid having to overwrite the constructor and call parent.
invokeAction()
Dispatches the controller action.
public
invokeAction(Closure $action, array<string|int, mixed> $args) : void
Parameters
- $action : Closure
-
The action closure.
- $args : array<string|int, mixed>
-
The arguments to be passed when invoking action.
Tags
isAction()
Method to check that an action is accessible from a URL.
public
isAction(string $action) : bool
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
- $action : string
-
The action to check.
Tags
Return values
bool —Whether the method is accessible from a URL.
isAutoRenderEnabled()
Returns true if an action should be rendered automatically.
public
isAutoRenderEnabled() : bool
Tags
Return values
boolloadComponent()
Add a component to the controller's registry.
public
loadComponent(string $name[, array<string, mixed> $config = [] ]) : Component
This method will also set the component to a property. For example:
$this->loadComponent('Authentication.Authentication');
Will result in a Authentication
property being set.
Parameters
- $name : string
-
The name of the component to load.
- $config : array<string, mixed> = []
-
The config for the component.
Tags
Return values
ComponentloadModel()
Loads and constructs repository objects required by this object
public
loadModel([string|null $modelClass = null ][, string|null $modelType = null ]) : RepositoryInterface
Use LocatorAwareTrait::fetchTable()
instead.
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
- $modelClass : string|null = null
-
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
. - $modelType : string|null = null
-
The type of repository to load. Defaults to the getModelType() value.
Tags
Return values
RepositoryInterface —The model instance created.
log()
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
public
log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
- $message : string
-
Log message.
- $level : string|int = LogLevel::ERROR
-
Error level.
- $context : array<string|int, mixed>|string = []
-
Additional log data relevant to this message.
Return values
bool —Success of log write.
middleware()
Register middleware for the controller.
public
middleware(MiddlewareInterface|Closure|string $middleware[, array<string, mixed> $options = [] ]) : void
Parameters
- $middleware : MiddlewareInterface|Closure|string
-
Middleware.
- $options : array<string, mixed> = []
-
Valid options:
-
only
: (array|string) Only run the middleware for specified actions. -
except
: (array|string) Run the middleware for all actions except the specified ones.
-
Tags
modelFactory()
Override a existing callable to generate repositories of a given type.
public
modelFactory(string $type, LocatorInterface|callable $factory) : void
Parameters
- $type : string
-
The name of the repository type the factory function is for.
- $factory : LocatorInterface|callable
-
The factory function used to create instances.
paginate()
Handles pagination of records in Table objects.
public
paginate([Table|Query|string|null $object = null ][, array<string, mixed> $settings = [] ]) : ResultSet|ResultSetInterface
Will load the referenced Table object, and have the paginator
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
- $object : Table|Query|string|null = null
-
Table to paginate (e.g: Table instance, 'TableName' or a Query object)
- $settings : array<string, mixed> = []
-
The settings/configuration used for pagination.
Tags
Return values
ResultSet|ResultSetInterface —Query results
redirect()
Redirects to given $url, after turning off $this->autoRender.
public
redirect(UriInterface|array<string|int, mixed>|string $url[, int $status = 302 ]) : Response|null
Parameters
- $url : UriInterface|array<string|int, mixed>|string
-
A string, array-based URL or UriInterface instance.
- $status : int = 302
-
HTTP status code. Defaults to
302
.
Tags
Return values
Response|nullreferer()
Returns the referring URL for this request.
public
referer([array<string|int, mixed>|string|null $default = '/' ][, bool $local = true ]) : string
Parameters
- $default : array<string|int, mixed>|string|null = '/'
-
Default URL to use if HTTP_REFERER cannot be read from headers
- $local : bool = true
-
If false, do not restrict referring URLs to local server. Careful with trusting external sources.
Return values
string —Referring URL
render()
Instantiates the correct view class, hands it its data, and uses it to render the view output.
public
render([string|null $template = null ][, string|null $layout = null ]) : Response
Parameters
- $template : string|null = null
-
Template to use for rendering
- $layout : string|null = null
-
Layout to use
Tags
Return values
Response —A response object containing the rendered view.
set()
Saves a variable or an associative array of variables for use inside a template.
public
set(array<string|int, mixed>|string $name[, mixed $value = null ]) : $this
Parameters
- $name : array<string|int, mixed>|string
-
A string or an array of data.
- $value : mixed = null
-
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.
Return values
$thissetAction()
Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
public
setAction(string $action, mixed ...$args) : mixed
Refactor your code use redirect()
instead of forwarding actions.
Examples:
setAction('another_action');
setAction('action_with_parameters', $parameter1);
Parameters
- $action : string
-
The new action to be 'redirected' to. Any other parameters passed to this method will be passed as parameters to the new action.
- $args : mixed
-
Arguments passed to the action
Return values
mixed —Returns the return value of the called action
setEventManager()
Returns the Cake\Event\EventManagerInterface instance for this object.
public
setEventManager(EventManagerInterface $eventManager) : $this
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
- $eventManager : EventManagerInterface
-
the eventManager to set
Return values
$thissetModelType()
Set the model type to be used by this class
public
setModelType(string $modelType) : $this
Parameters
- $modelType : string
-
The model type
Return values
$thissetName()
Sets the controller name.
public
setName(string $name) : $this
Parameters
- $name : string
-
Controller name.
Tags
Return values
$thissetPlugin()
Sets the plugin name.
public
setPlugin(string|null $name) : $this
Parameters
- $name : string|null
-
Plugin name.
Tags
Return values
$thissetRequest()
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:
public
setRequest(ServerRequest $request) : $this
- $this->request - To the $request parameter
Parameters
- $request : ServerRequest
-
Request instance.
Return values
$thissetResponse()
Sets the response instance.
public
setResponse(Response $response) : $this
Parameters
- $response : Response
-
Response instance.
Tags
Return values
$thissetTableLocator()
Sets the table locator.
public
setTableLocator(LocatorInterface $tableLocator) : $this
Parameters
- $tableLocator : LocatorInterface
-
LocatorInterface instance.
Return values
$thisshutdownProcess()
Perform the various shutdown processes for this controller.
public
shutdownProcess() : ResponseInterface|null
Fire the Components and Controller callbacks in the correct order.
- triggers the component
shutdown
callback. - calls the Controller's
afterFilter
method.
Return values
ResponseInterface|nullstartupProcess()
Perform the startup process for this controller.
public
startupProcess() : ResponseInterface|null
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.
Return values
ResponseInterface|nullviewBuilder()
Get the view builder being used.
public
viewBuilder() : ViewBuilder
Return values
ViewBuilderviewClasses()
Get the View classes this controller can perform content negotiation with.
public
viewClasses() : array<string|int, string>
Each view class must implement the getContentType()
hook method
to participate in negotiation.
Tags
Return values
array<string|int, string>_setModelClass()
Set the modelClass property based on conventions.
protected
_setModelClass(string $name) : void
If the property is already set it will not be overwritten
Parameters
- $name : string
-
Class name.
_templatePath()
Get the templatePath based on controller name and request prefix.
protected
_templatePath() : string
Return values
stringchooseViewClass()
Use the view classes defined on this controller to view selection based on content-type negotiation.
protected
chooseViewClass() : string|null
Return values
string|null —The chosen view class or null for no decision.