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\AuthComponentCake\Controller\Component\FlashComponentCake\Controller\Component\FormProtectionComponentCake\Controller\Component\PaginatorComponentCake\Controller\Component\RequestHandlerComponentCake\Controller\Component\SecurityComponentCake\Controller\ComponentRegistry|nullInstance of ComponentRegistry used to create Components
stringDefault class name for new event objects.
Cake\Event\EventManagerInterface|nullInstance 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.
stringThe model type to use.
Cake\ORM\Locator\LocatorInterface|nullTable locator instance
Cake\View\ViewBuilder|nullThe view builder instance being used.
boolSet to true to automatically render the view after action logic.
string|nullThis object's default table alias.
arrayMiddlewares list.
string|nullThis object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
stringThe name of this controller. Controller names are plural, named after the model they manipulate.
arraySettings for pagination.
string|nullAutomatically set to the name of a plugin.
Cake\Http\ServerRequestAn 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\ResponseAn 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.
stringafterFilter(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|voidbeforeFilter(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|voidbeforeRedirect(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|voidbeforeRender(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|voidchooseViewClass(): string|null
Use the view classes defined on this controller to view selection based on content-type negotiation.
string|nullcomponents(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\ComponentRegistrycreateView(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\ViewCake\View\Exception\MissingViewExceptiondisableAutoRender(): $this
Disable automatic action rendering.
$thisdispatchEvent(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\EventInterfaceenableAutoRender(): $this
Enable automatic action rendering.
$thisfetchTable(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\TableCake\Core\Exception\CakeExceptiongetAction(): Closure
Get the closure for action to be invoked by ControllerFactory.
ClosureCake\Controller\Exception\MissingActionExceptiongetEventManager(): 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\EventManagerInterfacegetMiddleware(): array
Get middleware to be applied for this controller.
arraygetModelType(): string
Get the model type to be used by this class
stringgetName(): string
Returns the controller name.
stringgetPlugin(): string|null
Returns the plugin name.
string|nullgetRequest(): Cake\Http\ServerRequest
Gets the request instance.
Cake\Http\ServerRequestgetResponse(): Cake\Http\Response
Gets the response instance.
Cake\Http\ResponsegetTableLocator(): Cake\ORM\Locator\LocatorInterface
Gets the table locator.
Cake\ORM\Locator\LocatorInterfaceimplementedEvents(): 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.
voidinvokeAction(Closure $action, array $args): void
Dispatches the controller action.
Closure $action The action closure.
array $args The arguments to be passed when invoking action.
voidUnexpectedValueExceptionisAction(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.
boolReflectionExceptionisAutoRenderEnabled(): bool
Returns true if an action should be rendered automatically.
boolloadComponent(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\ComponentExceptionloadModel(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\RepositoryInterfaceCake\Datasource\Exception\MissingModelExceptionUnexpectedValueExceptionlog(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.
boolmiddleware(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.voidmodelFactory(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.
voidpaginate(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\ResultSetInterfaceRuntimeExceptionredirect(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|nullreferer(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.
stringrender(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\Responseset(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.
$thissetAction(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
mixedsetEventManager(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
$thissetModelType(string $modelType): $this
Set the model type to be used by this class
string $modelType The model type
$thissetName(string $name): $this
Sets the controller name.
string $name Controller name.
$thissetPlugin(string|null $name): $this
Sets the plugin name.
string|null $name Plugin name.
$thissetRequest(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.
$thissetResponse(Cake\Http\Response $response): $this
Sets the response instance.
Cake\Http\Response $response Response instance.
$thissetTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
Sets the table locator.
Cake\ORM\Locator\LocatorInterface $tableLocator LocatorInterface instance.
$thisshutdownProcess(): 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|nullstartupProcess(): 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|nullviewBuilder(): Cake\View\ViewBuilder
Get the view builder being used.
Cake\View\ViewBuilderviewClasses(): 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\AuthComponentCake\Controller\Component\FlashComponentCake\Controller\Component\FormProtectionComponentCake\Controller\Component\PaginatorComponentCake\Controller\Component\RequestHandlerComponentCake\Controller\Component\SecurityComponentInstance of ComponentRegistry used to create Components
Cake\Controller\ComponentRegistry|nullDefault class name for new event objects.
stringInstance of the Cake\Event\EventManager this object is using to dispatch inner events.
Cake\Event\EventManagerInterface|nullA list of overridden model factory functions.
array<callableCake\Datasource\Locator\LocatorInterface>The model type to use.
stringTable locator instance
Cake\ORM\Locator\LocatorInterface|nullThe view builder instance being used.
Cake\View\ViewBuilder|nullSet to true to automatically render the view after action logic.
boolThis object's default table alias.
string|nullMiddlewares list.
arrayThis 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|nullThe name of this controller. Controller names are plural, named after the model they manipulate.
Set automatically using conventions in Controller::__construct().
stringSettings for pagination.
Used to pre-configure pagination preferences for the various tables your controller will be paginating.
arrayAutomatically set to the name of a plugin.
string|nullAn 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\ServerRequestAn 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