CakePHP

Page 193

09775ch09final

7/1/08

9:49 PM

Page 171

CHAPTER 9 ■ HELPERS

Customizing Helper Variables You’ve built a custom helper with functions to handle specific operations. But what about customizing the variables used by built-in helpers? Suppose you want to perform the same operation that is already written in the HTML helper but you want to change the display of the HTML helper’s output. Rather than build a completely different helper to fit your customized output, you can simply alter the variables the HTML helper uses and then call the needed function. Recall that you already created the App helper file in the app/ directory. There, you can intercept the global variables used by any helper and insert your own code. Open the cake/ libs/view/helpers/html.php file to read the raw HTML helper code. Scroll down to line 47 and see the $tags array (as shown in Listing 9-7). Listing 9-7. The HTML Helper’s $tags Array 47 var $tags = array( 48–96 … 97 'error' => '<div%s>%s</div>' 98 ); I’ve deliberately skipped over lines 48–96 in Listing 9-7 because the same idea is repeated throughout the array. The HTML helper uses this array to construct the HTML tags that are returned with its functions. Changing one of these keys and values will change the output for the whole HTML helper. In other words, whenever the HTML helper, in any function, displays the error tag, you can replace its value on line 97 with your own, and all error tags will reflect the change. The most direct way to alter the $tags array would be to create your own in the App helper. However, you would have to specify all tags used by the HTML helper, which would result in duplication between the App helper and the HTML helper. To trim the amount of data you supply to affect the $tags array, you can use the Helper object’s loadConfig() function with the __construct() function. In the App helper, insert the contents of Listing 9-8. Listing 9-8. The __construct() Function in the App Helper 1 2 3 4

function __construct() { parent::__construct(); $this->loadConfig(); }

This function will be called when any helper is included in a controller. Line 2 makes sure that all the default constructions of the Helper object are performed first. Then, on line 3 you’ve included the loadConfig() function. By default, this function will search for the tags.php file in the app/config folder and merge its contents with the $tags array. You can specify which file to merge by including its name in the function: $this->loadConfig('blog');

171


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.