<?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>engfer(s) &#187; Zend Framework</title>
	<atom:link href="http://www.engfers.com/category/zend-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.engfers.com</link>
	<description>» scrumptious blog &#38; code » nothing more, nothing less</description>
	<lastBuildDate>Thu, 14 Apr 2011 22:04:28 +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>Smarty Plugin To Replace Zend Framework View Helper &#8220;Url&#8221;</title>
		<link>http://www.engfers.com/2008/10/24/smarty-plugin-to-replace-zend-framework-view-helper-url/</link>
		<comments>http://www.engfers.com/2008/10/24/smarty-plugin-to-replace-zend-framework-view-helper-url/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 22:05:36 +0000</pubDate>
		<dc:creator>engfer</dc:creator>
				<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[smarty]]></category>

		<guid isPermaLink="false">http://www.engfers.com/?p=715</guid>
		<description><![CDATA[We made a Smarty plugin to replace Zend Framework&#8217;s Zend_Controller_Action_Helper_Url functionality that was lost by doing a full integration of Smarty and Zend. Sometimes, Integrations Come with Setbacks In a previous post here at engfers.com, we talked about how to &#8230; <a href="http://www.engfers.com/2008/10/24/smarty-plugin-to-replace-zend-framework-view-helper-url/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We made a Smarty plugin to replace Zend Framework&#8217;s Zend_Controller_Action_Helper_Url functionality that was lost by doing a full integration of Smarty and Zend.<br />
<span id="more-715"></span><div align="center"><script type="text/javascript"><!--
google_ad_client = "pub-9461422058527053";
google_ad_slot = "5057152483";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div></p>
<h3 class="hrule"><span style="color: #3366ff;">Sometimes, Integrations Come with Setbacks</span></h3>
<p>In a previous post here at engfers.com, we talked about how to <strong><a href="http://www.engfers.com/2008/10/17/how-to-make-smarty-the-default-view-for-your-zend-action-controllers/">fully integrate the PHP templating engine, Smarty, with the Zend Framework</a></strong> by replacing the implementation of the viewRenderer&#8217;s <code>Zend_View_Interface</code> with a <code>Zend_View_Smarty</code> implementation.</p>
<p>Unfortunately, by using this solution, any reference to the <code>$this</code> pointer in the template land references the Smarty object instead of <code>Zend_View</code>.</p>
<p>Well, the Smarty object <strong>doesn&#8217;t </strong>contain the nice &#8220;url-ifier&#8221; (<code>$this-&gt;url()</code>). With the &#8220;url-ifier&#8221; (<code>Zend_Controller_Action_Helper_Url</code>), one could specify the module, controller, action and request parameters as an associative array parameter, and it would generate a nice and pretty url for you.</p>
<p>Well, we wanted that functionality back!</p>
<h4><span style="color: #3366ff;">Hacks</span></h4>
<p>At first thought, one might be tempted to use the <code>{php}...{/php}</code> template tags in Smarty. <strong>Don&#8217;t</strong> do it! It&#8217;ll totally invalidate the whole point of using Smarty and it&#8217;s <em>ugly as snot</em>.</p>
<p>Another creative way to accomplish this is to do some sort of <a href="http://my.opera.com/zomg/blog/2007/11/03/the-best-smarty-zend-view-helpers-solution">fancy template variable assignment that gives you access to some method, object or whateve</a>r; <strong>don&#8217;t</strong> do this either.</p>
<p>The correct way to accomplish the task at hand is to make a <strong>Smarty plugin</strong> that <em>emulates </em>the functionality of whatever <code>Zend_Controller_Action_Helper_Url</code> did.</p>
<h3 class="hrule"><span style="color: #3366ff;">The Smarty Plugin </span></h3>
<p>Read the comments section in the code and see the examples section for template implementations.</p>
<h4><span style="color: #ff0000;">The Code: function.zend_url.php<br />
</span></h4>
<p>Just copy this and plop it in your <code>$smarty-&gt;plugins_dir</code> and call it <span style="color: #ff0000;"><strong><code>function.zend_url.php</code></strong></span></p>
<pre>// @depends Zend_Controller_Front from Zend Framework

/**
 * Type:     function
 * Name:     zend_url
 * Purpose:  Generate a url based on the default front
 *  controller's router rules. It's just a proxy method to
 *  the router's assemble() method. This was meant to
 *  replace view calls to $this-&gt;url();
 *
 * Parameters:
 *  module (optional)
 *    - module name
 *  controller (optional)
 *    - controlle name
 *  action (optional)
 *    - action name
 *  zend_url_name (optional)
 *    - see Zend_Controller_Router_Interface::assemble()
 *  zend_url_reset (optional)
 *    - see Zend_Controller_Router_Interface::assemble()
 *  zend_url_encode (optional)
 *    - see Zend_Controller_Router_Interface::assemble()
 *
 * Other url parameters can be passed via 'key="value"'
 *
 * Example:
 * {zend_url module="myapp" controller="blog"
 *    action="edit" postId="232" user="admin"}
 *
 * @author David Engfer
 *
 * @param array containg attrubtes
 * @param Smarty
 */
function smarty_function_zend_url($params, &amp;$smarty) {
    // Defaults as specified by assemble()
    $urlParams = array();
    $name = null;
    $reset = false;
    $encode = true;

    // Capture the module
    if (isset($params['module'])) {
        $urlParams['module'] = $params['module'];
        unset($params['module']);
    }

    // Capture the controller
    if (isset($params['controller'])) {
        $urlParams['controller'] = $params['controller'];
        unset($params['controller']);
    }

    // Capture the action
    if (isset($params['action'])) {
        $urlParams['action'] = $params['action'];
        unset($params['action']);
    }

    // Capture if a route name is specified
    if (isset($params['zend_url_name'])) {
        print_r ($params['zend_url_name']);
        $name = $params['zend_url_name'];
        unset($params['zend_url_name']);
    }

    // Capture if resetting the route is specified
    if (isset($params['zend_url_reset'])) {
        $reset = $params['zend_url_reset'] == "true"
        ? true
        : false;
        unset($params['zend_url_reset']);
    }

    // Capture if encoding parameters is specified
    if (isset($params['zend_url_encode'])) {
        $encode = $params['zend_url_encode'] == "false"
            ? false
            : true;
        unset($params['zend_url_encode']);
    }

    // Grab rest of the params and add them to urlParams
    foreach ( $params as $key =&gt; $val ) {
        $urlParams[ $key ] = $val;
        unset( $params[ $key ] );
    }

    // Assemble the url and pass it back
    return Zend_Controller_Front::getInstance()
        -&gt;getRouter()-&gt;assemble(
            $urlParams,
            $name,
            $reset,
            $encode );
}</pre>
<h4><span style="color: #ff0000;">Example Usage:</span></h4>
<p>If we were on the page http://servername/blog/post/index/231 (post/index.tpl), the following would generate:</p>
<pre>{zend_url}</pre>
<ul>
<li>http://servername/blog/post/index</li>
</ul>
<pre>{zend_url action="edit" id="231"}</pre>
<ul>
<li>http://servername/blog/post/edit/id/231</li>
</ul>
<pre>{zend_url module="blog2" controller="user" action="edit"
   name="john"}</pre>
<ul>
<li>http://servername/blog2/user/edit/name/john</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.engfers.com/2008/10/24/smarty-plugin-to-replace-zend-framework-view-helper-url/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>How To Make Smarty the Default View for Your Zend Action Controllers</title>
		<link>http://www.engfers.com/2008/10/17/how-to-make-smarty-the-default-view-for-your-zend-action-controllers/</link>
		<comments>http://www.engfers.com/2008/10/17/how-to-make-smarty-the-default-view-for-your-zend-action-controllers/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 08:13:54 +0000</pubDate>
		<dc:creator>engfer</dc:creator>
				<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[smarty]]></category>

		<guid isPermaLink="false">http://www.engfers.com/?p=530</guid>
		<description><![CDATA[There are many articles and enough documentation out there on how to include the Smarty PHP templating engine into your Zend Framework action controllers; however, there was no solution out there describing how to truly incorporate Smarty as the default &#8230; <a href="http://www.engfers.com/2008/10/17/how-to-make-smarty-the-default-view-for-your-zend-action-controllers/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-612 aligncenter" title="Smarty with Zend Framework" src="http://www.engfers.com/wp-content/uploads/2008/10/smarty_zend.png" alt="" width="350" height="74" /></p>
<p>There are many articles and enough documentation out there on how to <span style="color: #ff0000;"><strong>include </strong></span>the Smarty PHP templating engine into your Zend Framework action controllers; however, there was no solution out there describing how to truly <span style="color: #ff0000;"><strong>incorporate </strong></span>Smarty as the <strong><em>default </em></strong>view renderer, so I decided to figure it out and show you how.no<br />
<div align="center"><script type="text/javascript"><!--
google_ad_client = "pub-9461422058527053";
google_ad_slot = "5057152483";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div><span id="more-530"></span><br />
<span style="color: #ff0000;"><strong><span style="text-decoration: underline;">UPDATE</span>: 2008-10-17 10:25: I found a better way to do all of this that uses the default view renderer to do the work for you. In fact the SmartyControllerAction class wasn&#8217;t even needed anymore.</strong></span></p>
<h3 class="hrule"><span style="color: #3366ff;">Partial Implementations</span></h3>
<p>One day, I realized that the phtml view files for my Zend Framework project looked like unmaintainable scary hack (with &lt;?php &#8230; ?&gt; tags and shorttags abound), so I wanted to refactor my code to make it a bit more maintainable and readable.</p>
<p>I stumbled upon an article in the Zend Devzone about <a href="http://devzone.zend.com/node/view/id/120"><strong>Integrating Smarty with the Zend Framework</strong></a>. After reading the article and checking Smarty out, I decided that I wanted to use Smarty as my view renderer.</p>
<p>I found several articles &#8220;on the webz&#8221; on &#8220;integrating&#8221; the two; however, all of the &#8220;integrations&#8221; required you to specify the output template file name at the end of each controller action method as you can see below (it was more like an inclusion than an integration)&#8230;</p>
<p style="text-align: center;"><a href="http://devzone.zend.com/node/view/id/120"><img class="size-full wp-image-614 aligncenter" title="Smarty &quot;included&quot; but not really incorporated" src="http://www.engfers.com/wp-content/uploads/2008/10/zendbad.png" alt="" width="411" height="375" /></a></p>
<p>I also found on the Zend Framework Documentation page for &#8220;<strong><a href="http://framework.zend.com/manual/en/zend.view.scripts.html#zend.view.scripts.templates.interface">50.3.2.2. Template Systems Using Zend_View_Interface</a></strong>&#8221; where they actually have an example implementation of a Zend_View_Smarty class which implemented the <em>Zend_View_Interface</em> (which is the closest I could find to my desired Zend + Smary incorporation).</p>
<p>However, at the bottom of the section, they talk about how to use this example Zend_View_Smary, but again I was disappointed to find out I would have to<strong> call render() at the end of every controller&#8217;s action method!</strong> See below&#8230;</p>
<p style="text-align: center;"><img class="size-full wp-image-616 aligncenter" title="Even Zend's own Smarty view doesn't &quot;incorporate&quot;" src="http://www.engfers.com/wp-content/uploads/2008/10/zend_viewbad.png" alt="" /></p>
<p>Since no one described how to fully incorporate, I thought I would do it myself and let you know my results.</p>
<h3 class="hrule"><span style="color: #3366ff;">The Proper Marriage of Zend Framework and Smarty</span></h3>
<p><strong>Well, why couldn&#8217;t I just call render() at the end of each controller&#8217;s action?</strong></p>
<p>Call me lazy; call me a stickler. However, I really liked how the Zend_Controller_Action&#8217;s default view renderer used the names of controllers and actions to <strong>automatically determine what .phtml file to display</strong>; I thought it was really nifty.</p>
<p style="text-align: center;"><img class="size-full wp-image-597 aligncenter" title="zendoldsetup" src="http://www.engfers.com/wp-content/uploads/2008/10/zendoldsetup.png" alt="" width="342" height="235" /></p>
<p style="text-align: left;">As you can see above, the default view renderer would assume there was a &#8220;views/scripts/&#8221; directory inside your application module which would contain directories of .phtml files, where the directory names were the same name as the controller, and the .phtml files under those directories would be the name of each respective controller&#8217;s actions.</p>
<p>I wanted to see that <strong>same sort of automatic determination</strong> of the view script when I used the Smarty templating engine as my view renderer.</p>
<p style="text-align: center;"><img class="size-full wp-image-600 aligncenter" title="zendnewsetup" src="http://www.engfers.com/wp-content/uploads/2008/10/zendnewsetup.png" alt="" width="342" height="274" /></p>
<p style="text-align: left;">This also included not making the extra call to render() at the end of each controller&#8217;s action methods.</p>
<p style="text-align: left;">It ended up being <em>easier </em>than I thought.</p>
<h4><span style="color: #3366ff;">Zend_View_Smarty Class<br />
</span></h4>
<p style="text-align: left;">I used the Zend_View_Smarty class from the Zend Documentation page, mentioned <em>earlier, </em>as the view.</p>
<p style="text-align: left;">It just required three lines of code to be changed for it to work. In the setScriptPath() method, the smarty template_dir is set; well, I also wanted it to set the cache_dir, config_dir and compile_dir properties to be in the same relative directory as the current $path passed in.</p>
<pre>class Zend_View_Smarty implements Zend_View_Interface {
    ...

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path) {
        if (is_readable($path)) {
            $this-&gt;_smarty-&gt;template_dir = $path;

            // Convert the smarty paths into view paths
            $this-&gt;_smarty-&gt;compile_dir = dirname( $path )
                    . '/' . $this-&gt;_smarty-&gt;compile_dir;
            $this-&gt;_smarty-&gt;cache_dir = dirname( $path )
                    . '/' . $this-&gt;_smarty-&gt;cache_dir;
            $this-&gt;_smarty-&gt;config_dir = dirname( $path )
                    . '/' . $this-&gt;_smarty-&gt;config_dir;
            return;
        }

        throw new Exception('Invalid path provided');
    }

    ...
}</pre>
<h4><span style="color: #3366ff;">Time to Use Them&#8230;</span></h4>
<p>Now you want actually use the class.</p>
<p><strong>1)</strong> Create config ini file&#8230;</p>
<pre>; Config properties for Smarty templates
[Smarty]
debugging = false
force_compile = true
compile_check = true

;; Location to smarty plugins
plugins_dir = ../library/my_smarty_plugins

;; Caching
caching = false
cache_lifetime = -1

;; Dir Names to be converted to :moduleDir relative paths
cache_dir = cache
config_dir = config
template_dir = templates
compile_dir = templates_c</pre>
<p><strong>2) </strong>Edit your bootstrap file to contain the following&#8230;</p>
<pre>$smartyCfg = new Zend_Config_Ini( $configFile, 'Smarty', true );

include_once( 'Smarty/Smarty.class.php');
// Path to zend_view_smary.php
require_once( 'app/view/Zend_View_Smarty.php' );
$view = new Zend_View_Smarty(null, $smartyCfg );

// Use a modified view helper to render view scripts using Smarty
Zend_Loader::loadClass('Zend_Controller_Action_Helper_ViewRenderer');
$helper = new Zend_Controller_Action_Helper_ViewRenderer($view);

// Set the base script path RELATIVE TO THIS FILE
$helper-&gt;setViewBasePathSpec(':moduleDir/views/'
                              . $smartyCfg-&gt;template_dir);
// Change view suffix from phtml to tpl
$helper-&gt;setViewSuffix('tpl');

// Replace the default View Renderer with the Smarty modified one
Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer');
Zend_Controller_Action_HelperBroker::addHelper($helper);</pre>
<p><span style="text-decoration: underline;">The important parts to take away from the above code are the following:</span></p>
<pre>$helper-&gt;setViewBasePathSpec(':moduleDir/views/'
                              . $smartyCfg-&gt;template_dir);</pre>
<p>If this line is incorrect, you most likely will be having some problems.</p>
<p>Any path spec makes use of the following variables that get replaced at dispatch time:</p>
<ul>
<li><code>:moduleDir</code>
<ul>
<li>Replaced with the modules dir + / + module name</li>
</ul>
</li>
<li><code>:module</code>
<ul>
<li>Replaced with dispatched module name</li>
</ul>
</li>
<li><code>:controller</code>
<ul>
<li>Replaced with dispatched controller name</li>
</ul>
</li>
<li><code>:action</code>
<ul>
<li>Replaced with dispatched action name</li>
</ul>
</li>
<li><code>:suffix</code>
<ul>
<li>Replaced with view</li>
</ul>
</li>
</ul>
<p>In the examples below, you will see that I map to &#8220;:moduleDir/views/&#8221; + &#8220;templates&#8221; for my base spec path.</p>
<pre>$helper-&gt;setViewSuffix('tpl');</pre>
<p>This line will switch the default view file suffix from .phtml to .tpl.</p>
<h4><span style="color: #3366ff;">An Example&#8230;</span></h4>
<p>The directory setup</p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-698" title="Example setup" src="http://www.engfers.com/wp-content/uploads/2008/10/exampleideal.png" alt="" width="451" height="425" /></p>
<p>The IndexController looks like most other simple controllers you have made&#8230;</p>
<pre>class IndexController extends Zend_Controller_Action {
    public function indexAction(){
        $this-&gt;view-&gt;name = "Frank Sinatra";

        $this-&gt;view-&gt;fruits = array(
            "apples",
            "bananas",
            "papayas",
            "peaches"
        );
    }
}</pre>
<p>The index action will look for an index.tpl file (via :action.:suffix) in the index/ directory (via :controller) of your views/ directory (via :moduleDir).</p>
<pre>{include file="header.tpl"}

&lt;div&gt;&lt;b&gt;This is the result of
          IndexController::indexAction()&lt;/b&gt;&lt;/div&gt;

&lt;br/&gt;

&lt;div&gt;Hello {$name}!&lt;/div&gt;

&lt;br/&gt;

&lt;div&gt;Here is {$name}'s favorite fruits:
&lt;ul&gt;
  {section name="favFruits" loop="$fruits"}
    &lt;li&gt;{$fruits[favFruits]}&lt;/li&gt;
  {/section}
&lt;/ul&gt;
&lt;/div&gt;

{include file="footer.tpl"}</pre>
<p>Combine it with the header.tpl</p>
<pre>&lt;html&gt;

&lt;head&gt;
  &lt;title&gt;Test Zend_View_Smarty App&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

Header Content
&lt;hr/&gt;</pre>
<p>and the footer.tpl</p>
<pre>&lt;hr/&gt;
Footer Content

&lt;/body&gt;
&lt;/html&gt;</pre>
<p style="text-align: left;">The final output works just as normal.</p>
<h3 class="hrule"><span style="color: #3366ff;">Download The Example&#8230;<br />
</span></h3>
<p>If you can think of any other features and or suggestions, let me know and I&#8217;ll add it into the view/controller-action classes. Thanks!</p>
<p style="padding-left: 30px;"><strong><a style="padding: 3px 0px 3px 30px; font-size: 150%; background: transparent url(http://www.engfers.com/wp-content/uploads/2008/10/zip.png) scroll no-repeat left center;" href="http://www.engfers.com/wp-content/uploads/2008/10/ZendSmarty_v4.zip">ZendSmarty_v4.zip</a></strong></p>
<p><div align="center"><script type="text/javascript"><!--
google_ad_client = "pub-9461422058527053";
google_ad_slot = "5057152483";
google_ad_width = 468;
google_ad_height = 60;
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div></p>
]]></content:encoded>
			<wfw:commentRss>http://www.engfers.com/2008/10/17/how-to-make-smarty-the-default-view-for-your-zend-action-controllers/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>

