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().
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.Cake\Controller\Component\AuthComponent
Cake\Controller\Component\FlashComponent
Cake\Controller\Component\FormProtectionComponent
Cake\Controller\Component\PaginatorComponent
Cake\Controller\Component\RequestHandlerComponent
Cake\Controller\Component\SecurityComponent
Cake\Controller\ComponentRegistry|null
Instance of ComponentRegistry used to create Components
string
Default class name for new event objects.
Cake\Event\EventManagerInterface|null
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
array<callableCake\Datasource\Locator\LocatorInterface>
A list of overridden model factory functions.
string
The model type to use.
Cake\ORM\Locator\LocatorInterface|null
Table locator instance
Cake\View\ViewBuilder|null
The view builder instance being used.
bool
Set to true to automatically render the view after action logic.
string|null
This object's default table alias.
array
Middlewares list.
string|null
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
string
The name of this controller. Controller names are plural, named after the model they manipulate.
array
Settings for pagination.
string|null
Automatically set to the name of a plugin.
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.
Cake\Http\Response
An instance of a Response object that contains information about the impending response
Constructor.
Magic accessor for model autoloading.
Magic setter for removed properties.
Set the modelClass property based on conventions.
Get the templatePath based on controller name and request prefix.
Called after the controller action is run and rendered.
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.
The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.
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.
Use the view classes defined on this controller to view selection based on content-type negotiation.
Get the component registry for this controller.
Constructs the view class instance based on the current configuration.
Disable automatic action rendering.
Wrapper for creating and dispatching events.
Enable automatic action rendering.
Convenience method to get a table instance.
Get the closure for action to be invoked by ControllerFactory.
Returns the Cake\Event\EventManager manager instance for this object.
Get middleware to be applied for this controller.
Get the model type to be used by this class
Returns the controller name.
Returns the plugin name.
Gets the request instance.
Gets the response instance.
Gets the table locator.
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
Initialization hook method.
Dispatches the controller action.
Method to check that an action is accessible from a URL.
Returns true if an action should be rendered automatically.
Add a component to the controller's registry.
Loads and constructs repository objects required by this object
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
Register middleware for the controller.
Override a existing callable to generate repositories of a given type.
Handles pagination of records in Table objects.
Redirects to given $url, after turning off $this->autoRender.
Returns the referring URL for this request.
Instantiates the correct view class, hands it its data, and uses it to render the view output.
Saves a variable or an associative array of variables for use inside a template.
Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
Returns the Cake\Event\EventManagerInterface instance for this object.
Set the model type to be used by this class
Sets the controller name.
Sets the plugin name.
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:
Sets the response instance.
Sets the table locator.
Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order.
Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order.
Get the view builder being used.
Get the View classes this controller can perform content negotiation with.
__construct(Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, string|null $name = null, Cake\Event\EventManagerInterface|null $eventManager = null, Cake\Controller\ComponentRegistry|null $components = 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.
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(string $name): Cake\Datasource\RepositoryInterface|null
Magic accessor for model autoloading.
string
$name Property name
Cake\Datasource\RepositoryInterface|null
__set(string $name, mixed $value): void
Magic setter for removed properties.
string
$name Property name.
mixed
$value Value to set.
void
_setModelClass(string $name): void
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
string
$name Class name.
void
_templatePath(): string
Get the templatePath based on controller name and request prefix.
string
afterFilter(Cake\Event\EventInterface $event): Cake\Http\Response|null|void
Called after the controller action is run and rendered.
Cake\Event\EventInterface
$event An Event instance
Cake\Http\Response|null|void
beforeFilter(Cake\Event\EventInterface $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.
Cake\Event\EventInterface
$event An Event instance
Cake\Http\Response|null|void
beforeRedirect(Cake\Event\EventInterface $event, 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.
Cake\Event\EventInterface
$event An Event instance
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.
Cake\Http\Response|null|void
beforeRender(Cake\Event\EventInterface $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.
Cake\Event\EventInterface
$event An Event instance
Cake\Http\Response|null|void
chooseViewClass(): string|null
Use the view classes defined on this controller to view selection based on content-type negotiation.
string|null
components(Cake\Controller\ComponentRegistry|null $components = null): Cake\Controller\ComponentRegistry
Get the component registry for this controller.
If called with the first parameter, it will be set as the controller $this->_components property
Cake\Controller\ComponentRegistry|null
$components optional Component registry.
Cake\Controller\ComponentRegistry
createView(string|null $viewClass = null): Cake\View\View
Constructs the view class instance based on the current configuration.
string|null
$viewClass optional Optional namespaced class name of the View class to instantiate.
Cake\View\View
Cake\View\Exception\MissingViewException
disableAutoRender(): $this
Disable automatic action rendering.
$this
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
Wrapper for creating and dispatching events.
Returns a dispatched event.
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).
Cake\Event\EventInterface
enableAutoRender(): $this
Enable automatic action rendering.
$this
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
Convenience method to get a table instance.
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.
Cake\ORM\Table
Cake\Core\Exception\CakeException
getAction(): Closure
Get the closure for action to be invoked by ControllerFactory.
Closure
Cake\Controller\Exception\MissingActionException
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.
Cake\Event\EventManagerInterface
getMiddleware(): array
Get middleware to be applied for this controller.
array
getModelType(): string
Get the model type to be used by this class
string
getName(): string
Returns the controller name.
string
getPlugin(): string|null
Returns the plugin name.
string|null
getRequest(): Cake\Http\ServerRequest
Gets the request instance.
Cake\Http\ServerRequest
getResponse(): Cake\Http\Response
Gets the response instance.
Cake\Http\Response
getTableLocator(): Cake\ORM\Locator\LocatorInterface
Gets the table locator.
Cake\ORM\Locator\LocatorInterface
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
public function implementedEvents() { return [ 'Order.complete' => 'sendEmail', 'Article.afterBuy' => 'decrementInventory', 'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true] ]; }
array<string, mixed>
initialize(): void
Initialization hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
void
invokeAction(Closure $action, array $args): void
Dispatches the controller action.
Closure
$action The action closure.
array
$args The arguments to be passed when invoking action.
void
UnexpectedValueException
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.
string
$action The action to check.
bool
ReflectionException
isAutoRenderEnabled(): bool
Returns true if an action should be rendered automatically.
bool
loadComponent(string $name, array<string, mixed> $config = []): Cake\Controller\Component
Add a component to the controller's registry.
This method will also set the component to a property. For example:
$this->loadComponent('Authentication.Authentication');
Will result in a Authentication
property being set.
string
$name The name of the component to load.
array<string, mixed>
$config optional The config for the component.
Cake\Controller\Component
Exception
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
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.
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.
Cake\Datasource\RepositoryInterface
Cake\Datasource\Exception\MissingModelException
UnexpectedValueException
log(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.
string
$message Log message.
string|int
$level optional Error level.
array|string
$context optional Additional log data relevant to this message.
bool
middleware(Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware, array<string, mixed> $options = []): void
Register middleware for the controller.
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.void
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
Override a existing callable to generate repositories of a given type.
string
$type The name of the repository type the factory function is for.
Cake\Datasource\Locator\LocatorInterface|callable
$factory The factory function used to create instances.
void
paginate(Cake\ORM\TableCake\ORM\Query|string|null $object = null, array<string, mixed> $settings = []): Cake\ORM\ResultSetCake\Datasource\ResultSetInterface
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.
Cake\ORM\TableCake\ORM\Query|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.
Cake\ORM\ResultSetCake\Datasource\ResultSetInterface
RuntimeException
redirect(Psr\Http\Message\UriInterface|array|string $url, int $status = 302): Cake\Http\Response|null
Redirects to given $url, after turning off $this->autoRender.
Psr\Http\Message\UriInterface|array|string
$url A string, array-based URL or UriInterface instance.
int
$status optional HTTP status code. Defaults to 302
.
Cake\Http\Response|null
referer(array|string|null $default = '/', bool $local = true): string
Returns the referring URL for this request.
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.
string
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.
string|null
$template optional Template to use for rendering
string|null
$layout optional Layout to use
Cake\Http\Response
set(array|string $name, mixed $value = null): $this
Saves a variable or an associative array of variables for use inside a template.
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.
$this
setAction(string $action, mixed ...$args): mixed
Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
Examples:
setAction('another_action'); setAction('action_with_parameters', $parameter1);
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
mixed
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.
Cake\Event\EventManagerInterface
$eventManager the eventManager to set
$this
setModelType(string $modelType): $this
Set the model type to be used by this class
string
$modelType The model type
$this
setName(string $name): $this
Sets the controller name.
string
$name Controller name.
$this
setPlugin(string|null $name): $this
Sets the plugin name.
string|null
$name Plugin name.
$this
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:
Cake\Http\ServerRequest
$request Request instance.
$this
setResponse(Cake\Http\Response $response): $this
Sets the response instance.
Cake\Http\Response
$response Response instance.
$this
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
Sets the table locator.
Cake\ORM\Locator\LocatorInterface
$tableLocator LocatorInterface instance.
$this
shutdownProcess(): Psr\Http\Message\ResponseInterface|null
Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order.
shutdown
callback.afterFilter
method.Psr\Http\Message\ResponseInterface|null
startupProcess(): Psr\Http\Message\ResponseInterface|null
Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order.
initialize
callbackbeforeFilter
.startup
methods.Psr\Http\Message\ResponseInterface|null
viewBuilder(): Cake\View\ViewBuilder
Get the view builder being used.
Cake\View\ViewBuilder
viewClasses(): array<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.
array<string>
Cake\Controller\Component\AuthComponent
Cake\Controller\Component\FlashComponent
Cake\Controller\Component\FormProtectionComponent
Cake\Controller\Component\PaginatorComponent
Cake\Controller\Component\RequestHandlerComponent
Cake\Controller\Component\SecurityComponent
Instance of ComponentRegistry used to create Components
Cake\Controller\ComponentRegistry|null
Default class name for new event objects.
string
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Cake\Event\EventManagerInterface|null
A list of overridden model factory functions.
array<callableCake\Datasource\Locator\LocatorInterface>
The model type to use.
string
Table locator instance
Cake\ORM\Locator\LocatorInterface|null
The view builder instance being used.
Cake\View\ViewBuilder|null
Set to true to automatically render the view after action logic.
bool
This object's default table alias.
string|null
Middlewares list.
array
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.
string|null
The name of this controller. Controller names are plural, named after the model they manipulate.
Set automatically using conventions in Controller::__construct().
string
Settings for pagination.
Used to pre-configure pagination preferences for the various tables your controller will be paginating.
array
Automatically set to the name of a plugin.
string|null
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.
Cake\Http\ServerRequest
An instance of a Response object that contains information about the impending response
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.4/class-Cake.Controller.Controller.html