Yesterday I stumbled upon a “tip” about using the AppHelper to extend the functionality of the core helpers. The author missed some functionality in the HtmlHelper, and as you shouldn’t modify any files in the “cake” folder, he created the AppHelper class (in app/app_helper.php) and added the new method there.
On a first glance this might look like it is a good idea: it works fine and you can access the method with $html->myMethod() in the views. Perfect. Only, on a conceptual level this approach is wrong (and CakePHP shouldn’t allow you to do such things).
To see why it is wrong, let’s do a little thought experiment with a less abstract example. We have a Dog. Dog is an Animal. A Dog can run and follow commands, we can say they are its “methods”. For some reason the guy who created the Dog forgot that a Dog can bark, and so our Dog doesn’t bark. But we want a barking Dog! We only have the power to modify Animal but not the Dog, so we add the bark feature to the Animal. Now our Dog barks. Fine. However, what’s that? A barking cow. Barking birds. Hm, something went wrong…
Ok, I think you see what the problem is ;-)
There are two possible solutions to help you to avoid this problem: you either use inheritance to create a new type of Dog or you use composition to create a new type of Animal that uses a Dog (weird example, I know).
Applied to the helper situation I mentioned at the beginning of this article, it means you either create your own helper which extends the HtmlHelper or you create your own helper which extends AppHelper and uses internally the HtmlHelper.
Happy baking :)