Extending CakePHP’s core components

Published on and tagged with cakephp  component

In a recent comment David Cournoyer shared a tip about extending CakePHP’s core components and I think it could also be useful for others.

Let’s say we want to add a method to the request handler component. And so we create a new class which inherits from the request handler component:

// app/controllers/components/my_request_handler.php
App::import('Component', 'RequestHandler');
class MyRequestHandlerComponent extends RequestHandlerComponent {
    public function example() {
        // do something
    }
}

To use this component, we have to add it to the $components array of our controller:

// app/app_controller.php
class AppController extends Controller {
    public $components = array('MyRequestHandler');	
}

Nothing new so far. However, a disadvantage of this approach is that you have to use the component in the following way:

$this->MyRequestHandler->isAjax();
$this->MyRequestHandler->example();

Wouldn’t it be nice if we could use it in the usual way?

$this->RequestHandler->isAjax();
$this->RequestHandler->example();

And yes, it is possible. For this purpose we have to override Controller::constructClasses():

// app/app_controller.php
class AppController extends Controller {
    public $components = array('MyRequestHandler');
	
    public function constructClasses() {
        parent::constructClasses();
        $this->RequestHandler = $this->MyRequestHandler;
    }
}

Happy baking!

12 comments baked

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License