<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cakebaker &#187; helper</title>
	<atom:link href="http://cakebaker.42dh.com/tags/helper/feed/" rel="self" type="application/rss+xml" />
	<link>http://cakebaker.42dh.com</link>
	<description>baking cakes with CakePHP</description>
	<lastBuildDate>Tue, 20 Dec 2011 15:29:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Specifying helpers for static pages</title>
		<link>http://cakebaker.42dh.com/2009/06/01/specifying-helpers-for-static-pages/</link>
		<comments>http://cakebaker.42dh.com/2009/06/01/specifying-helpers-for-static-pages/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 07:19:10 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=1201</guid>
		<description><![CDATA[In a recent comment I got asked how you can reference Javascript files from static pages (i.e. from files in app/views/pages) as &#8220;you can&#8217;t add the JavaScript helper, because there isn&#8217;t a controller&#8221;. Well, the assumption that there is no controller is wrong. There is one, the PagesController, though by default it is &#8220;hidden&#8221; in [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent <a href="http://cakebaker.42dh.com/2007/02/21/referencing-javascript-files/#comment-129496">comment</a> I got asked how you can reference Javascript files from static pages (i.e. from files in app/views/pages) as &#8220;you can&#8217;t add the JavaScript helper, because there isn&#8217;t a controller&#8221;.</p>
<p>Well, the assumption that there is no controller is wrong. There is one, the PagesController, though by default it is &#8220;hidden&#8221; in cake/libs/controller (unless you baked your project with the bake script, then you will also find a PagesController in app/controllers).</p>
<p>And this means you can specify the helpers you want to use in your static pages in the usual way: by adding them to the $helpers array of the PagesController resp. the AppController (app/app_controller.php), if you want to use the helpers in the views of more than one controller. Please do not edit the PagesController in the cake/libs/controller directory, but copy it to app/controllers and make the changes there.</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2009/06/01/specifying-helpers-for-static-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An idea for hacking core helpers</title>
		<link>http://cakebaker.42dh.com/2008/11/07/an-idea-for-hacking-core-helpers/</link>
		<comments>http://cakebaker.42dh.com/2008/11/07/an-idea-for-hacking-core-helpers/#comments</comments>
		<pubDate>Fri, 07 Nov 2008 09:14:51 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[ideas]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=936</guid>
		<description><![CDATA[In a recent comment by John I got asked whether there is a way to override a method of a core helper like HtmlHelper::link() without affecting the variables in the views (i.e. you can still use $html-&#62;link() instead of $myHtml-&#62;link()). There are at least two approaches to accomplish this (without touching core files). The first [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent <a href="http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/#comment-111961">comment</a> by <a href="http://www.flipflops.org">John</a> I got asked whether there is a way to override a method of a core helper like HtmlHelper::link() without affecting the variables in the views (i.e. you can still use $html-&gt;link() instead of $myHtml-&gt;link()). There are at least two approaches to accomplish this (without touching core files).</p>
<p>The first approach is to copy the HtmlHelper from the core (cake/libs/view/helpers/html.php) to the helpers folder of your application (app/views/helpers). And then you can modify this file as you like. Easy. The problem of this approach is the code duplication. If something in the core HtmlHelper is changed by the developers you have to reapply the changes in your own HtmlHelper&#8230;</p>
<p>The second approach is to replace the HtmlHelper with your own helper that extends the HtmlHelper. For this purpose you have to create a custom view class which overrides the _loadHelpers() method of the View. It&#8217;s probably best if I do a simple example to show the idea. </p>
<p>First we create our own helper:</p>
<pre>
<code>// app/views/helpers/example.php
App::import('Helper', 'Html');
class ExampleHelper extends HtmlHelper {
    public function link($title, $url = null, $htmlAttributes = array(), $confirmMessage = false, $escapeTitle = true) {
        return '&lt;a href="http://example.com"&gt;example&lt;/a&gt;';
    }
}</code>
</pre>
<p>Next, we create our custom view class:</p>
<pre>
<code>// app/views/example.php
class ExampleView extends View {
    public function &amp;_loadHelpers(&amp;$loaded, $helpers, $parent = null) {
        $loaded = parent::_loadHelpers($loaded, $helpers, $parent);
        $helper = 'Html';
		
        if (isset($loaded[$helper])) {
            App::import('Helper', 'Example');
            $loaded[$helper] = new ExampleHelper();
	
            // everything from here on is copied from View::_loadHelpers()
		
            $vars = array('base', 'webroot', 'here', 'params', 'action', 'data', 'themeWeb', 'plugin');
            $c = count($vars);

            for ($j = 0; $j &lt; $c; $j++) {
                $loaded[$helper]-&gt;{$vars[$j]} = $this-&gt;{$vars[$j]};
            }

            if (!empty($this-&gt;validationErrors)) {
                $loaded[$helper]-&gt;validationErrors = $this-&gt;validationErrors;
            }

            if (is_array($loaded[$helper]-&gt;helpers) &amp;&amp; !empty($loaded[$helper]-&gt;helpers)) {
                $loaded =&amp; $this-&gt;_loadHelpers($loaded, $loaded[$helper]-&gt;helpers, $helper);
            }
        }
		
        return $loaded;
    }
}</code>
</pre>
<p>You probably wonder why I override _loadHelpers() and not _loadHelper(). Well, the reason is simple, there is no _loadHelper() method in the View class. And so I have to copy the code to setup a helper from the parent method. Not very clean, I know&#8230;</p>
<p>The last step is to specify that we want to use the view class we created above. We can do this in the AppController with:</p>
<pre>
<code>// app/app_controller.php
class AppController extends Controller {
    public $view = 'Example';
}</code>
</pre>
<p>Now, all links in our views should point to example.com. </p>
<p>The obvious disadvantage of this approach is that it is a hack ;-)  And I&#8217;m not sure whether it works to 100%. Use it on your own risk!</p>
<p>Personally, I would like to see the approach described by grigri (see his <a href="http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/#comment-110708">comment</a>) in the core (or something similar): &#8220;It would be great if the cake helpers were really named &#8216;BaseHtmlHelper&#8217; with an empty class &#8216;HtmlHelper&#8217; which is loaded from the cake folder if not present in the app folder.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/11/07/an-idea-for-hacking-core-helpers/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>The sequence of helper callbacks</title>
		<link>http://cakebaker.42dh.com/2008/10/23/the-sequence-of-helper-callbacks/</link>
		<comments>http://cakebaker.42dh.com/2008/10/23/the-sequence-of-helper-callbacks/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 08:25:14 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=906</guid>
		<description><![CDATA[While experimenting with the helper callbacks I noticed something I didn&#8217;t expect. Have a look at the following helper implementing the callback methods: class ExampleHelper extends AppHelper { public function beforeLayout() { echo 'beforeLayout'; } public function afterLayout() { echo 'afterLayout'; } public function beforeRender() { echo 'beforeRender'; } public function afterRender() { echo 'afterRender'; [...]]]></description>
			<content:encoded><![CDATA[<p>While experimenting with the helper callbacks I noticed something I didn&#8217;t expect.</p>
<p>Have a look at the following helper implementing the callback methods:</p>
<pre>
<code>class ExampleHelper extends AppHelper {
    public function beforeLayout() {
        echo 'beforeLayout';
    }

    public function afterLayout() {
        echo 'afterLayout';
    }
	
    public function beforeRender() {
        echo 'beforeRender';
    }
	
    public function afterRender() {
        echo 'afterRender';
    }
}</code>
</pre>
<p>What will be the output if you have a simple view and you add this helper to the $helpers array of the respective controller? </p>
<p>Personally I would have expected an output like:</p>
<pre>
<code>beforeLayout
&lt;html&gt;...
beforeRender
the content of the view
afterRender
...&lt;/html&gt;
afterLayout</code>
</pre>
<p>But to my surprise the output is quite different:</p>
<pre>
<code>beforeRender
beforeLayout
afterLayout
&lt;html&gt;...
the content of the view
afterRender
...&lt;/html&gt;</code>
</pre>
<p>I&#8217;m not sure whether this output is generated due to bugs in the rendering process or because it is the intended output&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/10/23/the-sequence-of-helper-callbacks/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t (ab)use the AppHelper to extend the core helpers</title>
		<link>http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/</link>
		<comments>http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/#comments</comments>
		<pubDate>Sat, 18 Oct 2008 08:58:22 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=900</guid>
		<description><![CDATA[Yesterday I stumbled upon a &#8220;tip&#8221; about using the AppHelper to extend the functionality of the core helpers. The author missed some functionality in the HtmlHelper, and as you shouldn&#8217;t modify any files in the &#8220;cake&#8221; folder, he created the AppHelper class (in app/app_helper.php) and added the new method there. On a first glance this [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I stumbled upon a &#8220;tip&#8221; about using the AppHelper to extend the functionality of the core helpers. The author missed some functionality in the HtmlHelper, and as you shouldn&#8217;t modify any files in the &#8220;cake&#8221; folder, he created the AppHelper class (in app/app_helper.php) and added the new method there. </p>
<p>On a first glance this might look like it is a good idea: it works fine and you can access the method with $html-&gt;myMethod() in the views. Perfect. Only, on a conceptual level this approach is wrong (and CakePHP shouldn&#8217;t allow you to do such things).</p>
<p>To see why it is wrong, let&#8217;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 &#8220;methods&#8221;. For some reason the guy who created the Dog forgot that a Dog can bark, and so our Dog doesn&#8217;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&#8217;s that? A barking cow. Barking birds. Hm, something went wrong&#8230;</p>
<p>Ok, I think you see what the problem is ;-)  </p>
<p>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). </p>
<p>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. </p>
<p>Happy baking :)</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/10/18/dont-abuse-the-apphelper-to-extend-the-core-helpers/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>An idea for loading helpers in the view</title>
		<link>http://cakebaker.42dh.com/2008/08/22/an-idea-for-loading-helpers-in-the-view/</link>
		<comments>http://cakebaker.42dh.com/2008/08/22/an-idea-for-loading-helpers-in-the-view/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 15:20:15 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[ideas]]></category>
		<category><![CDATA[view]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=724</guid>
		<description><![CDATA[In the comments to my previous article, &#8220;An alternative to requestAction&#8220;, it was mentioned that it is illogical to define helpers in the controller but to use them in views. (Thanks to Rafael Bandeira and Tarique Sani) That&#8217;s indeed a bit illogical if you think about it. It would be more logical to define the [...]]]></description>
			<content:encoded><![CDATA[<p>In the comments to my previous article, &#8220;<a href="http://cakebaker.42dh.com/2008/08/20/an-alternative-to-requestaction/">An alternative to requestAction</a>&#8220;, it was mentioned that it is illogical to define helpers in the controller but to use them in views. (Thanks to <a href="http://rafaelbandeira3.wordpress.com/">Rafael Bandeira</a> and <a href="http://www.sanisoft.com/blog/author/tariquesani/">Tarique Sani</a>)</p>
<p>That&#8217;s indeed a bit illogical if you think about it. It would be more logical to define the helpers directly where they are needed, in the views.</p>
<p>After some experimenting and digging in the source of the View class I found a relatively clean way to accomplish that by using a custom view class. </p>
<p>Ok, here is what I did. First I created a custom view class called &#8220;AppView&#8221; in app/views/app.php. It contains one method to load the helpers, which is later used in the views. I also had to override the constructor to support &#8220;global&#8221; helpers (i.e. they can be used in all views). So instead of defining them in the AppController they are now defined in the $helpers array of this custom view. FormHelper, HtmlHelper, and SessionHelper do not have to be defined, they are automatically loaded by CakePHP.</p>
<pre>
<code>// app/views/app.php
class AppView extends View {
    public $helpers = array('Navigation');
	
    public function __construct(&amp;$controller, $register = true) {
        $globalHelpers = $this-&gt;helpers;
        parent::__construct($controller, $register);
        $this-&gt;loadHelpers(array_merge($this-&gt;helpers, $globalHelpers));
    }
	
    public function loadHelpers($helperNames) {
        $helpers = $this-&gt;_loadHelpers($this-&gt;loaded, $helperNames);

        foreach ($helpers as $helper) {
            $name = str_replace('Helper', '', get_class($helper));
            $this-&gt;$name = $helper;
        }
    }
}</code>
</pre>
<p>To use this custom view class, I have to tell the AppController to do so by setting the $view property:</p>
<pre>
<code>// app/app_controller.php
class AppController extends Controller {
    public $view = 'App';
    ...
}</code>
</pre>
<p>And finally I can load and use the desired helpers in the views like:</p>
<pre>
<code>&lt;?php 
$this-&gt;loadHelpers(array('CamelCase')); 
echo $this-&gt;CamelCase-&gt;getSomething();
echo $this-&gt;Form-&gt;create('MyModel');
...
?&gt;</code>
</pre>
<p>As you can see from the example above, the usage of the helpers is different from what you are used to. Instead of $form-&gt;create() I used $this-&gt;Form-&gt;create(). It&#8217;s more to write, but I think it is more consistent with the rest of the framework. </p>
<p>What do you think about this approach?</p>
<p>Update (2008-08-28): Thanks to Rafael Bandeira&#8217;s idea it is no longer necessary to call the loadHelpers() method in your views, just copy the following method to the AppView and it will auto-load the helpers when they are needed:</p>
<pre>
<code>public function __get($property) {
    $this-&gt;loadHelpers(array($property));
    return $this-&gt;{$property};
}</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/08/22/an-idea-for-loading-helpers-in-the-view/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Defining and accessing helpers</title>
		<link>http://cakebaker.42dh.com/2008/07/21/defining-and-accessing-helpers/</link>
		<comments>http://cakebaker.42dh.com/2008/07/21/defining-and-accessing-helpers/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 16:53:35 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=634</guid>
		<description><![CDATA[If you add a helper to the $helpers array of your controller, then it doesn&#8217;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&#8217;s methods in your view with: $navigation-&#62;someMethod(); If you use $Navigation instead of $navigation, then it [...]]]></description>
			<content:encoded><![CDATA[<p>If you add a helper to the $helpers array of your controller, then it doesn&#8217;t matter whether the first character is lower- or uppercase:</p>
<pre>
public $helpers = array('Navigation');

or

public $helpers = array('navigation');
</pre>
<p>In both cases, you access the helper&#8217;s methods in your view with:</p>
<pre>
$navigation-&gt;someMethod();
</pre>
<p>If you use $Navigation instead of $navigation, then it causes a &#8220;call to a member function on a non-object&#8221; error.</p>
<p>If you use a helper from within another helper, the behavior changes and now it matters whether the first character of the helper&#8217;s name is lower- or uppercase in the $helpers array. Is the first character uppercased as in the example below:</p>
<pre>
// in your helper
public $helpers = array('Navigation');
</pre>
<p>Then you also have to use the uppercased name to access the helper&#8217;s methods, or you will get an error (with a lowercased name it is just the other way around):</p>
<pre>
$this-&gt;Navigation-&gt;someMethod();

vs.

$this-&gt;navigation-&gt;someMethod(); // causes an error
</pre>
<p>It&#8217;s one of those little pitfalls I encounter from time to time ;-)</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/07/21/defining-and-accessing-helpers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Defining an interval for minutes</title>
		<link>http://cakebaker.42dh.com/2008/04/04/defining-an-interval-for-minutes/</link>
		<comments>http://cakebaker.42dh.com/2008/04/04/defining-an-interval-for-minutes/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 15:43:22 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/?p=593</guid>
		<description><![CDATA[Just noticed that you can define an interval for minutes when using the form helper (up to now I used my own little helper to accomplish this). In the following example I use an interval of 15 minutes, i.e. the generated select box for the minutes only contains the values &#8220;00&#8243;, &#8220;15&#8243;, &#8220;30&#8243;, and &#8220;45&#8243;: [...]]]></description>
			<content:encoded><![CDATA[<p>Just noticed that you can define an interval for minutes when using the form helper (up to now I used my own little helper to accomplish this). </p>
<p>In the following example I use an interval of 15 minutes, i.e. the generated select box for the minutes only contains the values &#8220;00&#8243;, &#8220;15&#8243;, &#8220;30&#8243;, and &#8220;45&#8243;:</p>
<pre>
echo $form-&gt;input('start', array('type' =&gt; 'time', 'interval' =&gt; 15));
</pre>
<p>The default interval is one minute, but from the user&#8217;s point of view it is not that user-friendly to have a select box with 60 values, so I recommend to specify a different interval as shown above.</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2008/04/04/defining-an-interval-for-minutes/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Non-existing fields no longer supported in FormHelper</title>
		<link>http://cakebaker.42dh.com/2007/11/07/non-existing-fields-no-longer-supported-in-formhelper/</link>
		<comments>http://cakebaker.42dh.com/2007/11/07/non-existing-fields-no-longer-supported-in-formhelper/#comments</comments>
		<pubDate>Wed, 07 Nov 2007 08:43:11 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/2007/11/07/non-existing-fields-no-longer-supported-in-formhelper/</guid>
		<description><![CDATA[Yesterday, I noticed that a Javascript function stopped to work in my application. The reason was that the id of an input field used by this Javascript has changed from &#8220;ModelnameFieldname&#8221; to &#8220;Modelname&#8221;. As I didn&#8217;t change anything in my form it had to be an issue with the form helper. The &#8220;funny&#8221; thing was [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I noticed that a Javascript function stopped to work in my application. The reason was that the id of an input field used by this Javascript has changed from &#8220;ModelnameFieldname&#8221; to &#8220;Modelname&#8221;. As I didn&#8217;t change anything in my form it had to be an issue with the form helper. The &#8220;funny&#8221; thing was that the issue only occurred if the model existed (and the field didn&#8217;t exist in the model, as I learned later). </p>
<p>Obviously this issue was caused by a recent change in the FormHelper, and according to a <a href="https://trac.cakephp.org/ticket/3534">comment</a> by Nate it was intentionally: &#8220;In order to enable model association mapping for FormHelper, non-existent fields are no longer supported. In order for a field to be recognized, it must exist in the model&#8217;s schema, or have a validation rule defined in Model::$validate.&#8221;</p>
<p>Hm, I have to say I don&#8217;t like it as it introduces dependencies which are not obvious. So the following snippet may work in one case, but not in another case: </p>
<pre>
echo $form-&gt;create('Model');
echo $form-&gt;input('Model.field');
echo $form-&gt;end();
</pre>
<p>If the model and the field exist, then the correct code is generated. The same if the model doesn&#8217;t exist. But if the model exists, and the field not, it generates wrong code (i.e. all input fields for non-existing model fields will have the same id). So, be careful when using virtual fields.</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2007/11/07/non-existing-fields-no-longer-supported-in-formhelper/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>How to write and test your own head helper</title>
		<link>http://cakebaker.42dh.com/2007/09/28/how-to-write-and-test-your-own-head-helper/</link>
		<comments>http://cakebaker.42dh.com/2007/09/28/how-to-write-and-test-your-own-head-helper/#comments</comments>
		<pubDate>Fri, 28 Sep 2007 14:54:15 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/2007/09/28/how-to-write-and-test-your-own-head-helper/</guid>
		<description><![CDATA[In CakePHP 1.1 the head helper by Miguel Ros was quite popular to add stuff to the head section of a HTML page from the view. CakePHP 1.2 provides such a functionality for referencing Javascript and CSS files. If you want to add something else to the head section, you have to write your own [...]]]></description>
			<content:encoded><![CDATA[<p>In CakePHP 1.1 the <a href="http://cakeforge.org/snippet/detail.php?type=snippet&#038;id=56">head helper</a> by Miguel Ros was quite popular to add stuff to the head section of a HTML page from the view. CakePHP 1.2 provides such a functionality for referencing <a href="http://cakebaker.42dh.com/2007/02/21/referencing-javascript-files/">Javascript</a> and <a href="http://cakebaker.42dh.com/2007/03/14/referencing-css-files/">CSS</a> files. If you want to add something else to the head section, you have to write your own helper. </p>
<p>Let&#8217;s write a simple helper which creates an author meta tag. </p>
<p>Usually you write first the test, and then the application code. But in this case I will make an exception, as I think it is easier to understand if I write first the application code and then the test.</p>
<p>Writing the helper is straight-forward: we have to get the view and add the meta tag to this view:</p>
<pre>
// app/views/helpers/head.php
class HeadHelper extends AppHelper {
    function authorMetaTag($authorName) {
        $metaTag = '&lt;meta name="author" content="'.$authorName.'"&gt;';
        $view = ClassRegistry::getObject('view');
        $view-&gt;addScript($metaTag);
    }
}
</pre>
<p>Before this helper can be used we have to add the following line to the head section of the (default) layout:</p>
<pre>
&lt;?php echo $scripts_for_layout; ?&gt;
</pre>
<p>With that we are ready to write our test (resp. we are finished with our work if we don&#8217;t write tests).</p>
<p>The test skeleton is easy:</p>
<pre>
class HeadHelperTest extends CakeTestCase {
    var $helper = null;

    function setUp() {
        $this-&gt;helper = new HeadHelper();
    }

    function testAuthorMetaTag() {
        $this-&gt;helper-&gt;authorMetaTag('cakebaker');
    }
}
</pre>
<p>As you have seen in the implementation of the helper, we retrieve a view object from the ClassRegistry. So to test our helper we also have to put a view object into the ClassRegistry. If you look at the source code of the view class constructor, you will see the view is automatically added to the ClassRegistry (to make sure the correct view is in the ClassRegistry we have to remove a possible view due to the behavior of ClassRegistry I explained in an earlier <a href="http://cakebaker.42dh.com/2007/09/20/dont-implement-a-known-concept-differently/">article</a>). And you will also see that the constructor expects a controller object. As we don&#8217;t have any controller, we will use the AppController for this purpose. </p>
<pre>
loadController(null);

class HeadHelperTest extends CakeTestCase {
    var $helper = null;

    function setUp() {
        $this-&gt;helper = new HeadHelper();
    }

    function testAuthorMetaTag() {
        ClassRegistry::removeObject('view');
        $view = new View(new AppController());
        $this-&gt;helper-&gt;authorMetaTag('cakebaker');
    }
}
</pre>
<p>The last step is to render the view resp. the layout of the view and to check whether our meta tag has been added. For this purpose we can use the regular expression I described in &#8220;<a href="http://cakebaker.42dh.com/2007/09/10/regular-expression-to-check-for-content-between-tags/">Regular expression to check for content between tags</a>&#8221; and which was improved by BurntSushi.</p>
<pre>
loadController(null);

class HeadHelperTest extends CakeTestCase {
    var $helper = null;

    function setUp() {
        $this-&gt;helper = new HeadHelper();
    }

    function testAuthorMetaTag() {
        ClassRegistry::removeObject('view');
        $view = new View(new AppController());
        $this-&gt;helper-&gt;authorMetaTag('cakebaker');
        $renderedLayout = $view-&gt;renderLayout('');
        $this-&gt;assertPattern('#&lt;head&gt;.*?&lt;meta name="author" content="cakebaker"&gt;.*?&lt;/head&gt;#si', $renderedLayout);
    }
}
</pre>
<p>Now, we can run the test and should get a green bar.</p>
<p>Happy testing :)</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2007/09/28/how-to-write-and-test-your-own-head-helper/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to use a helper in a controller</title>
		<link>http://cakebaker.42dh.com/2007/08/09/how-to-use-a-helper-in-a-controller/</link>
		<comments>http://cakebaker.42dh.com/2007/08/09/how-to-use-a-helper-in-a-controller/#comments</comments>
		<pubDate>Thu, 09 Aug 2007 12:27:17 +0000</pubDate>
		<dc:creator>cakebaker</dc:creator>
				<category><![CDATA[cakephp]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[helper]]></category>

		<guid isPermaLink="false">http://cakebaker.42dh.com/2007/08/09/how-to-use-a-helper-in-a-controller/</guid>
		<description><![CDATA[A question asked from time to time in the IRC channel is: &#8220;How can I use helper X in my controller?&#8221;. Well, helpers are not thought to be used in controllers. They are designed to be used in views. So whenever this question arises, you have to ask yourself (or others) whether you are doing [...]]]></description>
			<content:encoded><![CDATA[<p>A question asked from time to time in the IRC channel is: &#8220;How can I use helper X in my controller?&#8221;. </p>
<p>Well, helpers are not thought to be used in controllers. They are designed to be used in views. So whenever this question arises, you have to ask yourself (or others) whether you are doing something wrong and if there is no better solution.</p>
<p>Nonetheless, in some (rare) cases it can be useful to use a helper inside a controller to avoid code duplication. It can be accomplished in the following way:</p>
<pre>
class UsersController extends AppController {
    function index() {
        App::import('Helper', 'Html'); // loadHelper('Html'); in CakePHP 1.1.x.x
        $html = new HtmlHelper();
        debug($html-&gt;link('Cake!', 'http://cakephp.org'));
    }
}
</pre>
<p>Or, if you are using CakePHP 2.0, you can use the following approach:</p>
<pre>
class UsersController extends AppController {
    function index() {
        $view = new View($this);
        $html = $view->loadHelper('Html');
        debug($html-&gt;link('Cake!', 'http://cakephp.org'));
    }
}
</pre>
<p>Update 2007-08-13: m3nt0r has published a <a href="http://www.m3nt0r.de/blog/2007/08/12/cakephp-helpercomponent/">helper component</a> in his blog which allows you to use a helper like a component. The article is in German, but the code should be self-explanatory.<br />
Update 2008-06-07: Using App::import() instead of loadHelper() in the example. Thanks to mjamesd for the hint!<br />
Update 2011: Adding snippet for CakePHP 2.0</p>
]]></content:encoded>
			<wfw:commentRss>http://cakebaker.42dh.com/2007/08/09/how-to-use-a-helper-in-a-controller/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
	</channel>
</rss>

