Components
Components are packages of logic that are shared between controllers.CakePHP comes with a fantastic set of core components you can use to aid invarious common tasks. You can also create your own components. If you findyourself wanting to copy and paste things between controllers, you shouldconsider creating your own component to contain the functionality. Creatingcomponents keeps controller code clean and allows you to reuse code betweendifferent controllers.
For more information on the components included in CakePHP, check out thechapter for each component:
Configuring Components
Many of the core components require configuration. Some examples of componentsrequiring configuration are AuthComponent andCookie. Configuration for these components,and for components in general, is usually done via loadComponent()
in yourController’s initialize()
method or via the $components
array:
- class PostsController extends AppController
- {
- public function initialize()
- {
- parent::initialize();
- $this->loadComponent('Auth', [
- 'authorize' => 'Controller',
- 'loginAction' => ['controller' => 'Users', 'action' => 'login']
- ]);
- $this->loadComponent('Cookie', ['expires' => '1 day']);
- }
- }
You can configure components at runtime using the config()
method. Often,this is done in your controller’s beforeFilter()
method. The above couldalso be expressed as:
- public function beforeFilter(Event $event)
- {
- $this->Auth->config('authorize', ['controller']);
- $this->Auth->config('loginAction', ['controller' => 'Users', 'action' => 'login']);
- $this->Cookie->config('name', 'CookieMonster');
- }
Like helpers, components implement a config()
method that is used to get andset any configuration data for a component:
- // Read config data.
- $this->Auth->config('loginAction');
- // Set config
- $this->Csrf->config('cookieName', 'token');
As with helpers, components will automatically merge their $_defaultConfig
property with constructor configuration to create the $_config
propertywhich is accessible with config()
.
Aliasing Components
One common setting to use is the className
option, which allows you toalias components. This feature is useful when you want toreplace $this->Auth
or another common Component reference with a customimplementation:
- // src/Controller/PostsController.php
- class PostsController extends AppController
- {
- public function initialize()
- {
- $this->loadComponent('Auth', [
- 'className' => 'MyAuth'
- ]);
- }
- }
- // src/Controller/Component/MyAuthComponent.php
- use Cake\Controller\Component\AuthComponent;
- class MyAuthComponent extends AuthComponent
- {
- // Add your code to override the core AuthComponent
- }
The above would alias MyAuthComponent
to $this->Auth
in yourcontrollers.
Note
Aliasing a component replaces that instance anywhere that component is used,including inside other Components.
Loading Components on the Fly
You might not need all of your components available on every controlleraction. In situations like this you can load a component at runtime using theloadComponent()
method in your controller:
- // In a controller action
- $this->loadComponent('OneTimer');
- $time = $this->OneTimer->getTime();
Note
Keep in mind that components loaded on the fly will not have missedcallbacks called. If you rely on the beforeFilter
or startup
callbacks being called, you may need to call them manually depending on whenyou load your component.
Using Components
Once you’ve included some components in your controller, using them is prettysimple. Each component you use is exposed as a property on your controller. Ifyou had loaded up the Cake\Controller\Component\FlashComponent
in your controller, you could access it like so:
- class PostsController extends AppController
- {
- public function initialize()
- {
- parent::initialize();
- $this->loadComponent('Flash');
- }
- public function delete()
- {
- if ($this->Post->delete($this->request->getData('Post.id')) {
- $this->Flash->success('Post deleted.');
- return $this->redirect(['action' => 'index']);
- }
- }
Note
Since both Models and Components are added to Controllers asproperties they share the same ‘namespace’. Be sure to not give acomponent and a model the same name.
Creating a Component
Suppose our application needs to perform a complex mathematical operation inmany different parts of the application. We could create a component to housethis shared logic for use in many different controllers.
The first step is to create a new component file and class. Create the file insrc/Controller/Component/MathComponent.php. The basic structure for thecomponent would look something like this:
- namespace App\Controller\Component;
- use Cake\Controller\Component;
- class MathComponent extends Component
- {
- public function doComplexOperation($amount1, $amount2)
- {
- return $amount1 + $amount2;
- }
- }
Note
All components must extend Cake\Controller\Component
. Failingto do this will trigger an exception.
Including your Component in your Controllers
Once our component is finished, we can use it in the application’scontrollers by loading it during the controller’s initialize()
method.Once loaded, the controller will be given a new attribute named after thecomponent, through which we can access an instance of it:
- // In a controller
- // Make the new component available at $this->Math,
- // as well as the standard $this->Csrf
- public function initialize()
- {
- parent::initialize();
- $this->loadComponent('Math');
- $this->loadComponent('Csrf');
- }
When including Components in a Controller you can also declare aset of parameters that will be passed on to the Component’sconstructor. These parameters can then be handled bythe Component:
- // In your controller.
- public function initialize()
- {
- parent::initialize();
- $this->loadComponent('Math', [
- 'precision' => 2,
- 'randomGenerator' => 'srand'
- ]);
- $this->loadComponent('Csrf');
- }
The above would pass the array containing precision and randomGenerator toMathComponent::initialize()
in the $config
parameter.
Using Other Components in your Component
Sometimes one of your components may need to use another component.In this case you can include other components in your component the exact sameway you include them in controllers - using the $components
var:
- // src/Controller/Component/CustomComponent.php
- namespace App\Controller\Component;
- use Cake\Controller\Component;
- class CustomComponent extends Component
- {
- // The other component your component uses
- public $components = ['Existing'];
- // Execute any other additional setup for your component.
- public function initialize(array $config)
- {
- $this->Existing->foo();
- }
- public function bar()
- {
- // ...
- }
- }
- // src/Controller/Component/ExistingComponent.php
- namespace App\Controller\Component;
- use Cake\Controller\Component;
- class ExistingComponent extends Component
- {
- public function foo()
- {
- // ...
- }
- }
Note
In contrast to a component included in a controllerno callbacks will be triggered on a component’s component.
Accessing a Component’s Controller
From within a Component you can access the current controller through theregistry:
- $controller = $this->_registry->getController();
You can access the controller in any callback method from the eventobject:
- $controller = $event->getSubject();
Component Callbacks
Components also offer a few request life-cycle callbacks that allow them toaugment the request cycle.
beforeFilter
(Event $event)Is called before the controller’sbeforeFilter method, but after the controller’s initialize() method.
Is called after the controller’s beforeFiltermethod but before the controller executes the current actionhandler.
Is called after the controller executes the requested action’s logic,but before the controller renders views and layout.
Is called before output is sent to the browser.
- Is invoked when the controller’s redirectmethod is called but before any further action. If this methodreturns
false
the controller will not continue on to redirect therequest. The $url, and $response parameters allow you to inspect and modifythe location or any other headers in the response.