Poyan
Poyan

Reputation: 6643

CakePHP Sharing code between helpers

I have two types of data that are similar but different. They have some pieces of presentational code that they share but some that they implement differently.

I was thinking that I would have a factory function in a helper (Tracker is a TrackerHelper) like so;

$this->Tracker->getInstance("boolean"); // Returns a BooleanTrackerHelper

But I'm not sure how to return another helper from within another helper. I don't think I can just do a return new BooleanTrackerHelper() since CakePHP probably has it's own routines it wants to go through, and besides; that would force me to place all the classes in the same file.

There is a function in the manual that allows you to load a helper from within a view ($this->Helpers->load()) but I want to load a helper from another helper.

More generally; What do you do if you don't want to repeat in a bunch of different views that if data is of type A use helper A and if it's of type B use helper B, and where helpers A and B share some pieces of code.

There might be a brighter way of solving this, if so; please feel free to share!

Upvotes: 0

Views: 118

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

If you simply want to use one helper from within another helper, just include it in the $helpers array where you want to use it:

class TrackerHelper extends AppHelper {
    public $helpers = array('BooleanTracker');

    public function someMethod() {
        // Using the other helper
        $this->BooleanTracker->someOtherMethod();
    }
}

Upvotes: 1

Related Questions