Defining and accessing helpers

Published on and tagged with cakephp  helper

If you add a helper to the $helpers array of your controller, then it doesn’t matter whether the first character is lower- or uppercase:

public $helpers = array('Navigation');

or

public $helpers = array('navigation');

In both cases, you access the helper’s methods in your view with:

$navigation->someMethod();

If you use $Navigation instead of $navigation, then it causes a “call to a member function on a non-object” error.

If you use a helper from within another helper, the behavior changes and now it matters whether the first character of the helper’s name is lower- or uppercase in the $helpers array. Is the first character uppercased as in the example below:

// in your helper
public $helpers = array('Navigation');

Then you also have to use the uppercased name to access the helper’s methods, or you will get an error (with a lowercased name it is just the other way around):

$this->Navigation->someMethod();

vs.

$this->navigation->someMethod(); // causes an error

It’s one of those little pitfalls I encounter from time to time ;-)

4 comments baked

  • nate

    By convention, references to helpers any the $helpers array should *always* be in uppercase, regardless of whether or not they happen to work in lowercase. This should be reflected in any core or core-generated code.

  • cakebaker

    @nate: Thanks for your comment! I wasn’t aware there is such a convention ;-)

  • NOSLOW

    From the indispensable Cakesheet (http://cake-php.googlegroups.com/web/cakesheet.pdf)

    Conventions
    Class Name: MyCoolHelper
    Path: app/views/helpers/my_cool.php

    ;)

  • cakebaker

    @NOSLOW: *g*, thanks, I’m aware of those conventions, I just wasn’t aware that you should use $helpers = array(‘Form’); instead of $helpers = array(‘form’);

    In NoseRub, for example, we use $helpers = array(‘Form’); within a helper, but $helpers = array(‘form’); in a controller…

Bake a comment




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

© daniel hofstetter. Licensed under a Creative Commons License