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->request
. 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->response
allows you to manipulate all aspects of the response.
Controllers are created by Dispatcher
based on request parameters and routing. By default controllers and actions use conventional names. For example /posts/index
maps to PostsController::index()
. You can re-map URLs using Router::connect() or RouterBuilder::connect().
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(Event $event)
Called before each action. This is a good place to do general logic that applies to all actions.beforeRender(Event $event)
Called before the view is rendered.beforeRedirect(Event $event, $url, Response $response)
Called before a redirect is done.afterFilter(Event $event)
Called after each action is complete and after the view is rendered.__construct( Cake\Network\Request $request null , Cake\Network\Response $response null , string|null $name null , Cake\Event\EventManager|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\Network\Request
$request
optional null Cake\Network\Response
$response
optional null $name
optional null Cake\Event\EventManager
|null $eventManager
optional null Cake\Controller\ComponentRegistry
|null $components
optional null __get( string $name )
Magic accessor for model autoloading.
$name
boolean|object
__set( string $name , mixed $value )
Magic setter for removed properties.
$name
$value
_loadComponents( )
Loads the defined components using the Component factory.
_mergeControllerVars( )
Merge components, helpers vars from parent classes.
_viewPath( )
Get the viewPath based on controller name and request prefix.
string
afterFilter( Cake\Event\Event $event )
Called after the controller action is run and rendered.
Cake\Event\Event
$event
Cake\Network\Response|null
beforeFilter( Cake\Event\Event $event )
Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action.
Cake\Event\Event
$event
Cake\Network\Response|null
beforeRedirect( Cake\Event\Event $event , string|array $url , Cake\Network\Response $response )
The beforeRedirect method is invoked when the controller's redirect method is called but before any further action.
If the event is stopped the controller will not continue on to redirect the request. The $url and $status variables have same meaning as for the controller's method. You can set the event result to response instance or modify the redirect location using controller's response instance.
Cake\Event\Event
$event
$url
Cake\Network\Response
$response
Cake\Network\Response|null
beforeRender( Cake\Event\Event $event )
Called after the controller action is run, but before the view is rendered. You can use this method to perform logic or set view variables that are required on every request.
Cake\Event\Event
$event
Cake\Network\Response|null
components( Cake\Controller\ComponentRegistry|null $components null )
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 null Cake\Controller\ComponentRegistry
implementedEvents( )
Returns a list of all events that will fire in the controller during its lifecycle. You can override this function to add your own listener callbacks
array
Cake\Event\EventListenerInterface::implementedEvents()
initialize( )
Initialization hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
invokeAction( )
Dispatches the controller action. Checks that the action exists and isn't private.
mixed
LogicException
Cake\Controller\Exception\MissingActionException
isAction( string $action )
Method to check that an action is accessible from a URL.
Override this method to change which controller methods can be reached. The default implementation disallows access to all methods defined on Cake\Controller\Controller, and allows all public methods on all subclasses of this class.
$action
boolean
loadComponent( string $name , array $config [] )
Add a component to the controller's registry.
This method will also set the component to a property. For example:
$this->loadComponent('Acl.Acl');
Will result in a Toolbar
property being set.
$name
$config
optional [] Cake\Controller\Component
paginate( Cake\ORM\Table|string|Cake\ORM\Query|null $object null )
Handles pagination of records in Table objects.
Will load the referenced Table object, and have the PaginatorComponent paginate the query using the request date and settings defined in $this->paginate
.
This method will also make the PaginatorHelper available in the view.
Cake\ORM\Table
|string|Cake\ORM\Query
|null $object
optional null Cake\ORM\ResultSet
RuntimeException
redirect( string|array $url , integer $status 302 )
Redirects to given $url, after turning off $this->autoRender. Script execution is halted after the redirect.
$url
$status
optional 302 Cake\Network\Response|null
referer( string|null $default null , boolean $local false )
Returns the referring URL for this request.
$default
optional null $local
optional false string
render( string $view null , string $layout null )
Instantiates the correct view class, hands it its data, and uses it to render the view output.
$view
optional null $layout
optional null Cake\Network\Response
setAction( string $action )
Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect()
Examples:
setAction('another_action'); setAction('action_with_parameters', $parameter1);
$action
mixed
setRequest( Cake\Network\Request $request )
Sets the request objects and configures a number of controller properties based on the contents of the request. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are:
Cake\Network\Request
$request
shutdownProcess( )
Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order.
shutdown
callback.afterFilter
method.Cake\Network\Response|null
startupProcess( )
Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order.
initialize
callbackbeforeFilter
.startup
methods.Cake\Network\Response|null
dispatchEvent( string $name , array|null $data null , object|null $subject null )
Wrapper for creating and dispatching events.
Returns a dispatched event.
$name
$data
optional null $subject
optional null Cake\Event\Event
Cake\Event\EventDispatcherInterface::dispatchEvent()
eventManager( Cake\Event\EventManager $eventManager null )
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\EventManager
$eventManager
optional null Cake\Event\EventManager
Cake\Event\EventDispatcherInterface::eventManager()
tableLocator( Cake\ORM\Locator\LocatorInterface $tableLocator null )
Sets the table locator. If no parameters are passed, it will return the currently used locator.
Cake\ORM\Locator\LocatorInterface
$tableLocator
optional null Cake\ORM\Locator\LocatorInterface
log( mixed $msg , integer|string $level LogLevel::ERROR , string|array $context [] )
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
$msg
$level
optional LogLevel::ERROR $context
optional [] boolean
_mergeProperty( string $property , array $parentClasses , array $options )
Merge a single property with the values declared in all parent classes.
$property
$parentClasses
$options
_mergePropertyData( array $current , array $parent , boolean $isAssoc )
Merge each of the keys in a property together.
$current
$parent
$isAssoc
mixed
_mergeVars( array $properties , array $options [] )
Merge the list of $properties with all parent classes of the current class.
associative
- A list of properties that should be treated as associative arrays. Properties in this list will be passed through Hash::normalize() before merging.$properties
$options
optional [] _setModelClass( string $name )
Set the modelClass and modelKey properties based on conventions.
If the properties are already set they will not be overwritten
$name
loadModel( string|null $modelClass null , string|null $modelType null )
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.
$modelClass
optional null $modelType
optional null object
Cake\Datasource\Exception\MissingModelException
InvalidArgumentException
UnexpectedValueException
modelFactory( string $type , callable $factory )
Register a callable to generate repositories of a given type.
$type
$factory
modelType( string|null $modelType null )
Set or get the model type to be used by this class
$modelType
optional null string|$this
requestAction( string|array $url , array $extra [] )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
A basic example getting the return value of the controller action:
$variables = $this->requestAction('/articles/popular');
A basic example of request action to fetch a rendered page without the layout.
$viewHtml = $this->requestAction('/articles/popular', ['return']);
You can also pass the URL as an array:
$vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);
You can pass POST, GET, COOKIE and other data into the request using the appropriate keys. Cookies can be passed using the cookies
key. Get parameters can be set with query
and post data can be sent using the post
key.
$vars = $this->requestAction('/articles/popular', [ 'query' => ['page' => 1], 'cookies' => ['remember_me' => 1], ]);
By default actions dispatched with this method will use the global $_SERVER and $_ENV values. If you want to override those values for a request action, you can specify the values:
$vars = $this->requestAction('/articles/popular', [ 'environment' => ['CONTENT_TYPE' => 'application/json'] ]);
By default actions dispatched with this method will use the standard session object. If you want a particular session instance to be used, you need to specify it.
$vars = $this->requestAction('/articles/popular', [ 'session' => new Session($someSessionConfig) ]);
$url
$extra
optional [] mixed
createView( string|null $viewClass null )
Constructs the view class instance based on the current configuration.
$viewClass
optional null Cake\View\View
Cake\View\Exception\MissingViewException
set( string|array $name , string|array|null|boolean $value null )
Saves a variable or an associative array of variables for use inside a template.
$name
$value
optional null mixed
viewBuilder( )
Get the view builder being used.
Cake\View\ViewBuilder
viewOptions( string|array|null $options null , boolean $merge true )
Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView()
.
$options
optional null $merge
optional true true
.array
protected Cake\Event\EventManager
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
null
public string
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.
public string
The name of default View class.
$this->viewBuilder()->className()
instead.null
© 2005–2016 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.
http://api.cakephp.org/3.1/class-Cake.Controller.Controller.html