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 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.
Property Summary
-
$CheckHttpCache public @property
Cake\Controller\Component\CheckHttpCacheComponent
-
$Flash public @property
Cake\Controller\Component\FlashComponent
-
$FormProtection public @property
Cake\Controller\Component\FormProtectionComponent
-
$_components protected
Cake\Controller\ComponentRegistry|null
Instance of ComponentRegistry used to create Components
-
$_eventClass protected
string
Default class name for new event objects.
-
$_eventManager protected
Cake\Event\EventManagerInterface|null
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
-
$_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.
-
$defaultTable protected
string|null
This object's default table alias.
-
$middlewares protected
array
Middlewares list.
-
$name protected
string
The name of this controller. Controller names are plural, named after the model they manipulate.
-
$paginate protected
array<string, mixed>
Pagination settings.
-
$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. This object contains all the information about a request and several methods for reading additional information about the request.
-
$response protected
Cake\Http\Response
An instance of a Response object that contains information about the impending response
-
$viewClasses protected
list<string>
View classes for content negotiation.
Method Summary
-
__construct() public
Constructor.
-
__get() public
Magic accessor for the default table.
-
_templatePath() protected
Get the templatePath based on controller name and request prefix.
-
addViewClasses() public
Add View classes this controller can perform content negotiation with.
-
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.
-
chooseViewClass() protected
Use the view classes defined on this controller to view selection based on content-type negotiation.
-
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.
-
fetchTable() public
Convenience method to get a table instance.
-
getAction() public
Get the closure for action to be invoked by ControllerFactory.
-
getEventManager() public
Returns the Cake\Event\EventManager manager instance for this object.
-
getMiddleware() public
Get middleware to be applied for this controller.
-
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. You can override this function to add your own listener callbacks
-
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.
-
log() public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
-
middleware() public
Register middleware for the controller.
-
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.
-
setEventManager() public
Returns the Cake\Event\EventManagerInterface instance for this object.
-
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. Fire the Components and Controller callbacks in the correct order.
-
startupProcess() public
Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order.
-
viewBuilder() public
Get the view builder being used.
-
viewClasses() public
Get the View classes this controller can perform content negotiation with.
Method Detail
__construct() ¶ public
__construct(Cake\Http\ServerRequest $request, string|null $name = null, Cake\Event\EventManagerInterface|null $eventManager = null)
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
$request Request object for this controller. but expect that features that use the request parameters will not work.
-
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.
__get() ¶ public
__get(string $name): Cake\Controller\ComponentCake\ORM\Table|null
Magic accessor for the default table.
Parameters
-
string
$name Property name
Returns
Cake\Controller\ComponentCake\ORM\Table|null
_templatePath() ¶ protected
_templatePath(): string
Get the templatePath based on controller name and request prefix.
Returns
string
addViewClasses() ¶ public
addViewClasses(list<string> $viewClasses): $this
Add View classes this controller can perform content negotiation with.
Each view class must implement the getContentType()
hook method
to participate in negotiation.
Parameters
-
list<string>
$viewClasses View classes list.
Returns
$this
See Also
afterFilter() ¶ public
afterFilter(Cake\Event\EventInterfaceCake\Controller\Controller> $event): Cake\Http\Response|null|void
Called after the controller action is run and rendered.
Parameters
-
Cake\Event\EventInterfaceCake\Controller\Controller>
$event An Event instance
Returns
Cake\Http\Response|null|void
Links
beforeFilter() ¶ public
beforeFilter(Cake\Event\EventInterfaceCake\Controller\Controller> $event): Cake\Http\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.
Parameters
-
Cake\Event\EventInterfaceCake\Controller\Controller>
$event An Event instance
Returns
Cake\Http\Response|null|void
Links
beforeRedirect() ¶ public
beforeRedirect(Cake\Event\EventInterfaceCake\Controller\Controller> $event, Psr\Http\Message\UriInterface|array|string $url, Cake\Http\Response $response): Cake\Http\Response|null|void
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\EventInterfaceCake\Controller\Controller>
$event An Event instance
-
Psr\Http\Message\UriInterface|array|string
$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\EventInterfaceCake\Controller\Controller> $event): Cake\Http\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.
Parameters
-
Cake\Event\EventInterfaceCake\Controller\Controller>
$event An Event instance
Returns
Cake\Http\Response|null|void
Links
chooseViewClass() ¶ protected
chooseViewClass(): string|null
Use the view classes defined on this controller to view selection based on content-type negotiation.
Returns
string|null
components() ¶ public
components(): Cake\Controller\ComponentRegistry
Get the component registry for this controller.
Returns
Cake\Controller\ComponentRegistry
createView() ¶ public
createView(string|null $viewClass = null): Cake\View\View
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(): $this
Disable automatic action rendering.
Returns
$this
dispatchEvent() ¶ public
dispatchEvent(string $name, array $data = [], TSubject|null $subject = null): Cake\Event\EventInterface<TSubject>
Wrapper for creating and dispatching events.
Returns a dispatched event.
Parameters
-
string
$name Name of the event.
-
array
$data optional Any value you wish to be transported with this event to it can be read by listeners.
-
TSubject|null
$subject optional The object that this event applies to ($this by default).
Returns
Cake\Event\EventInterface<TSubject>
enableAutoRender() ¶ public
enableAutoRender(): $this
Enable automatic action rendering.
Returns
$this
fetchTable() ¶ public
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
Convenience method to get a table instance.
Parameters
-
string|null
$alias optional The alias name you want to get. Should be in CamelCase format. If
null
then the value of $defaultTable property is used.-
array<string, mixed>
$options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
Returns
Cake\ORM\Table
Throws
Cake\Core\Exception\CakeException
If `$alias` argument and `$defaultTable` property both are `null`.
See Also
getAction() ¶ public
getAction(): Closure
Get the closure for action to be invoked by ControllerFactory.
Returns
Closure
Throws
Cake\Controller\Exception\MissingActionException
getEventManager() ¶ public
getEventManager(): Cake\Event\EventManagerInterface
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
getMiddleware() ¶ public
getMiddleware(): array
Get middleware to be applied for this controller.
Returns
array
getRequest() ¶ public
getRequest(): Cake\Http\ServerRequest
Gets the request instance.
Returns
Cake\Http\ServerRequest
getResponse() ¶ public
getResponse(): Cake\Http\Response
Gets the response instance.
Returns
Cake\Http\Response
getTableLocator() ¶ public
getTableLocator(): Cake\ORM\Locator\LocatorInterface
Gets the table locator.
Returns
Cake\ORM\Locator\LocatorInterface
implementedEvents() ¶ public
implementedEvents(): array<string, mixed>
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
Example:
public function implementedEvents()
{
return [
'Order.complete' => 'sendEmail',
'Article.afterBuy' => 'decrementInventory',
'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true]
];
}
Returns
array<string, mixed>
initialize() ¶ public
initialize(): void
Initialization hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
Returns
void
invokeAction() ¶ public
invokeAction(Closure $action, array $args): void
Dispatches the controller action.
Parameters
-
Closure
$action The action closure.
-
array
$args The arguments to be passed when invoking action.
Returns
void
isAction() ¶ public
isAction(string $action): bool
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
isAutoRenderEnabled() ¶ public
isAutoRenderEnabled(): bool
Returns true if an action should be rendered automatically.
Returns
bool
loadComponent() ¶ public
loadComponent(string $name, array<string, mixed> $config = []): Cake\Controller\Component
Add a component to the controller's registry.
After loading a component it will be be accessible as a property through Controller::__get(). For example:
$this->loadComponent('Authentication.Authentication');
Will result in a $this->Authentication
being a reference to that component.
Parameters
-
string
$name The name of the component to load.
-
array<string, mixed>
$config optional The config for the component.
Returns
Cake\Controller\Component
Throws
Exception
log() ¶ public
log(Stringable|string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
Parameters
-
Stringable|string
$message Log message.
-
string|int
$level optional Error level.
-
array|string
$context optional Additional log data relevant to this message.
Returns
bool
middleware() ¶ public
middleware(Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware, array<string, mixed> $options = []): void
Register middleware for the controller.
Parameters
-
Psr\Http\Server\MiddlewareInterfaceClosure|string
$middleware Middleware.
-
array<string, mixed>
$options optional 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.
Returns
void
paginate() ¶ public
paginate(Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface|string|null $object = null, array<string, mixed> $settings = []): Cake\Datasource\Paging\PaginatedInterface
Handles pagination of records in Table objects.
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
-
Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface|string|null
$object optional Table to paginate (e.g: Table instance, 'TableName' or a Query object)
-
array<string, mixed>
$settings optional The settings/configuration used for pagination. See {@link \Cake\Controller\Controller::$paginate}.
Returns
Cake\Datasource\Paging\PaginatedInterface
Throws
Cake\Http\Exception\NotFoundException
When a page out of bounds is requested.
Links
redirect() ¶ public
redirect(Psr\Http\Message\UriInterface|array|string $url, int $status = 302): Cake\Http\Response|null
Redirects to given $url, after turning off $this->autoRender.
Parameters
-
Psr\Http\Message\UriInterface|array|string
$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(array|string|null $default = '/', bool $local = true): string
Returns the referring URL for this request.
Parameters
-
array|string|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
render() ¶ public
render(string|null $template = null, string|null $layout = null): Cake\Http\Response
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
Links
set() ¶ public
set(array|string $name, mixed $value = null): $this
Saves a variable or an associative array of variables for use inside a template.
Parameters
-
array|string
$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
setEventManager() ¶ public
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
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
setName() ¶ public
setName(string $name): $this
Sets the controller name.
Parameters
-
string
$name Controller name.
Returns
$this
setPlugin() ¶ public
setPlugin(string|null $name): $this
Sets the plugin name.
Parameters
-
string|null
$name Plugin name.
Returns
$this
setRequest() ¶ public
setRequest(Cake\Http\ServerRequest $request): $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:
- $this->request - To the $request parameter
Parameters
-
Cake\Http\ServerRequest
$request Request instance.
Returns
$this
setResponse() ¶ public
setResponse(Cake\Http\Response $response): $this
Sets the response instance.
Parameters
-
Cake\Http\Response
$response Response instance.
Returns
$this
setTableLocator() ¶ public
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
Sets the table locator.
Parameters
-
Cake\ORM\Locator\LocatorInterface
$tableLocator LocatorInterface instance.
Returns
$this
shutdownProcess() ¶ public
shutdownProcess(): Psr\Http\Message\ResponseInterface|null
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(): Psr\Http\Message\ResponseInterface|null
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(): Cake\View\ViewBuilder
Get the view builder being used.
Returns
Cake\View\ViewBuilder
viewClasses() ¶ public
viewClasses(): list<string>
Get the View classes this controller can perform content negotiation with.
Each view class must implement the getContentType()
hook method
to participate in negotiation.
Returns
list<string>
See Also
Property Detail
$_components ¶ protected
Instance of ComponentRegistry used to create Components
Type
Cake\Controller\ComponentRegistry|null
$_eventManager ¶ protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Type
Cake\Event\EventManagerInterface|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 ¶ protected
Pagination settings.
When calling paginate() these settings will be merged with the configuration you provide. Possible keys:
maxLimit
- The maximum limit users can choose to view. Defaults to 100limit
- The initial number of items per page. Defaults to 20.page
- The starting page, defaults to 1.allowedParameters
- A list of parameters users are allowed to set using request parameters. Modifying this list will allow users to have more influence over pagination, be careful with what you permit.className
- The paginator class to use. Defaults toCake\Datasource\Paging\NumericPaginator::class
.
Type
array<string, mixed>
$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