joshua.paling
joshua.paling

Reputation: 13952

How to extend or override functionality/methods of a CakePHP Core Helper

This: Cakephp Override HtmlHelper::link asks a very similar question, but there were no complete answers. Perhaps now, with Cake 2 out, there will be.

I want to create a custom helper that is a subclass of Cake's Paginator Helper. I want my new helper to override the 'numbers' method of Cake's Paginator helper, but I want it to inherit all other methods.

Is it possible to extend core helpers in this way? Obviously, I don't want to: modify the Cake Core; put unnecessary code in the AppHelper superclass; or duplicate the entire core Pagination Helper into my new helper.

Upvotes: 5

Views: 5615

Answers (2)

Derek Perkins
Derek Perkins

Reputation: 667

Adding onto Brelsnok's solution, aliasing is the right way to do it. If you add this code to your AppController.php file, anytime that you use the Paginator, it will use your extended class.

public $helpers = array(
'Paginator' => array('className' => 'PaginatorExt' )
);

Since the PaginatorExtHelper class already extends PaginatorHelper, the only function being overridden is numbers. Any calls to other Paginator methods will be handled by the core PaginatorHelper class, just as if it was a vanilla Cake install.

Upvotes: 11

Bart Gloudemans
Bart Gloudemans

Reputation: 1221

Create the file PaginatorExtHelper.php in your View/Helper/ folder. It could look something like below.
And instead of initiating $helpers = array('Paginator'); do $helpers = array('PaginatorExt');

<?php
App::uses('PaginatorHelper', 'View/Helper');

class PaginatorExtHelper extends PaginatorHelper {

    public function numbers($options = array()) {
        // logic here


        return $out;
    }
}
?>

By implementing only public function numbers() you inherit the other functions.

Upvotes: 5

Related Questions