<?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>Ryan&#039;s Blog &#187; Zend Framework</title>
	<atom:link href="http://www.rmauger.co.uk/tags/zend-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rmauger.co.uk</link>
	<description>Randomness will get you everywhere.</description>
	<lastBuildDate>Thu, 05 May 2011 14:35:49 +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>Using Twig with Zend Framework</title>
		<link>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/</link>
		<comments>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/#comments</comments>
		<pubDate>Wed, 04 May 2011 21:07:34 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Content Management]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Twig]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[templating system]]></category>
		<category><![CDATA[twig]]></category>
		<category><![CDATA[zf]]></category>

		<guid isPermaLink="false">http://www.rmauger.co.uk/?p=177</guid>
		<description><![CDATA[Twig, in short, is a templating system for PHP. But PHP is already a templating system many would argue! Well, I wouldn&#8217;t argue against that point. However, with the recent excitement in the air in the PHP Community about Symfony 2, I thought it worth checking out. Mostly I thought they were silly things that [...]]]></description>
			<content:encoded><![CDATA[<p>Twig, in short, is a templating system for PHP. But PHP is already a templating system many would argue! Well, I wouldn&#8217;t argue against that point. However, with the recent excitement in the air in the PHP Community about Symfony 2, I thought it worth checking out.<br />
Mostly I thought they were silly things that were not really needed unless you had a team of designers to work with, however, during my exploration, a couple of things occurred to me that I had not considered about templating systems before. One being the enforced separation of concerns they provide; you simply cannot do anything from inside them which you shouldn&#8217;t be, keeping your presentation very very clean. The second, being that they&#8217;re not all as terrible as Smarty.</p>
<p><span id="more-177"></span></p>
<h2>Installing Twig</h2>
<p>This really couldn&#8217;t get a lot simpler with pear:</p>
<pre>    $ pear channel-discover pear.twig-project.org
    $ pear install twig/Twig</pre>
<p>or, you can use the Git or Subversion repos as detailed on the projects website: <a href="http://www.twig-project.org/doc/intro.html">http://www.twig-project.org/doc/intro.html</a></p>
<p><strong>The Application Resource</strong></p>
<p>Setting up a ZF application resource for twig is a snip! The minimal config required to set up a Twig instance, is exactly that, minimal!</p>
<p>Simple create the class &#8220;Core_Resource_Twig&#8221; and place it in library/Core/Resource/Twig.php and consider the following code:</p>
<pre>&lt;?php

class Core_Resource_Twig extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @var Twig_Environment
     */
    protected $twig;

    public function init()
    {
        $options = $this-&gt;getOptions();
        $loader = new Twig_Loader_Filesystem($options['templateDir']);
        $this-&gt;twig = new Twig_Environment(
                $loader,
                $options['options']
        );
        return $this-&gt;twig;
    }
}</pre>
<p>All we are doing here, is creating an instance of the Filesystem Twig loader, which loads templates from files, and then passing that in to the Twig Environment, along with the rest of the options from our config, which in brief, would now look something like this:</p>
<pre>
[production]
autoloaderNamespaces[] = "Twig_"
pluginPaths.Core_Resource = APPLICATION_PATH "/../library/Core/Resource"

; FRONT CONTROLLER
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.controllerDirectory.default = APPLICATION_PATH "/controllers"
resources.frontController.noViewRenderer = true

; TWIG
resources.twig.templateDir = APPLICATION_PATH "/templates"
resources.twig.options.cache = APPLICATION_PATH "/../cache/twig"

[development : production]
resources.twig.options.debug = true
resources.twig.options.auto_reload = true
</pre>
<p>That now gives us two things, a configured Twig instance, and an application resource to hold it, which will be present in the invoke args in your controller. so for the next step, we stitch it together, and make it more useable, to make things super simple, a base controller class is useful here. The reason for a base controller class rather than an action helper is simple, performance, and simplicity; no need for the complexity or auto-rendering anything, we will simply call a method at the end of each action.</p>
<p>Given that we are now using twig, this has two benefits, we avoid the overhead of how ZF looks up the view name to decide which view template to render, which is a part of the bottleneck of ZF, and additionally, it matches more closely to the other documentation you&#8217;ll find on Twig elsewhere, and we are doing things in a slightly different manner to how we would use Zend_View, so why try to emulate it, when we are using something very different!</p>
<pre>&lt;?php

abstract class Core_Controller extends Zend_Controller_Action
{
    public function twig($template, array $vars)
    {
        $twig = $this-&gt;getBootstrap()-&gt;getResource('twig');

        $template = $twig-&gt;loadTemplate($template);
        $this-&gt;getResponse()-&gt;appendBody(
            $template-&gt;render($vars),
            'default'
        );
    }
}</pre>
<h2>Rendering the template</h2>
<p>Now that we have our base controller class, we can now use our template, in this manner from our action:</p>
<pre>&lt;?php

class IndexController extends Core_Controller
{
    /**
     * @var Core_Service_Posts
     */
    protected $service;

    public function init()
    {
        $this-&gt;service = new Core_Service_Posts();
    }

    public function indexAction()
    {
        $recent = $this-&gt;service-&gt;recentPosts();
        $this-&gt;twig('home.twig', array(
            'recent' =&gt; $recent,
        ));
    }

    public function viewAction()
    {
        $id = $this-&gt;getRequest()-&gt;getParam('id', false);
        if (false === $id) {
            throw new Core_InvalidIdException('No ID Present');
        }

        $paste = $this-&gt;service-&gt;byId($id);

        $this-&gt;twig('view-post.twig', array(
            'post' =&gt; $paste,
        ));
    }

}</pre>
<p>In this example, you have the indexAction, taking the service for the posts for the application, and passing the recent posts to the template, and in the view action, taking the selected post, and passes it to the template, with the selection of template for the action being passed as the first argument to our twig method we added to the base controller class.</p>
<p>And now, you can find examples and documentation on how to put together your twig templates here <a href="http://www.twig-project.org/documentation">http://www.twig-project.org/documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rmauger.co.uk/2011/05/using-twig-with-zend-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Why the Zend Framework Actionstack is Evil</title>
		<link>http://www.rmauger.co.uk/2009/03/why-the-zend-framework-actionstack-is-evil/</link>
		<comments>http://www.rmauger.co.uk/2009/03/why-the-zend-framework-actionstack-is-evil/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 11:14:34 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Action Stack]]></category>
		<category><![CDATA[Dispatch Loop]]></category>
		<category><![CDATA[Fat Models]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Thin Controllers]]></category>

		<guid isPermaLink="false">http://www.rmauger.co.uk/?p=45</guid>
		<description><![CDATA[The action stack seems to be a useful component to some people when starting out with the Zend Framework. This component is a seemingly un-needed part of the framework, as there really is no use-case for it which cannot be simplified with the use of a partial view, which reads data directly from the model, [...]]]></description>
			<content:encoded><![CDATA[<p>The action stack seems to be a useful component to some people when starting out with the <a href="http://framework.zend.com/" target="_blank">Zend Framework</a>. This component is a seemingly un-needed part of the framework, as there really is no use-case for it which cannot be simplified with the use of a partial view, which reads data directly from the model, possibly with a view helper alongside to provide some additional logic function, such as deciding on which view partial to use.</p>
<p>This part of the Framework causes the dispatch to loop. This is a costly process, as it involves quite alot. It also adds some further issues to your application design, such as where you should put code. for example if you have some code in your predispatch, and your looping through two actions in that controller, that code will be run twice. This is obviously, not good, and quite un-needed. Further complications can be added when it comes time to add ACL or authentication.</p>
<p><span id="more-45"></span></p>
<p>There is an even worse part of this feature, the <a title="The Action View Helper" href="http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.action">Action View Helper</a>. This helper basically creates an additional dispatch, copying the request object, and creating a loop-within-a-loop . The setting up of the dispatch process is a costly one, anyone who has profiled their code will have seen just how much of the process of a <a title="Zend Framework" href="http://framework.zend.com/" target="_blank">Zend Framework</a> application this eats up. Creating a whole extra dispatch must be a <strong>bad</strong> idea, even the <a title="Increasing performance of Zend Framework Applications" href="http://framework.zend.com/manual/en/performance.html" target="_blank">Zend Framework Performance Guide</a> notes this fact</p>
<p>So, lets go through some reasons for this being bad.</p>
<h2>Why its bad</h2>
<h3>Performance</h3>
<p>Every time you go through the dispatch process, there are a number of things which are done, which will be completly un-nessicary for your action, namely calling preDispatch and postDispatch for each action which is called. This often results in questions in #zftalk of &#8220;Why is my ACL being called twice?&#8221;. If you have an ACL being built in your preDispatch (as many people quite rightly do) this means if you have 3 calls to different actions, your ACL will be built, and queried 3 times, and if you haven&#8217;t cached your ACL object, this may incur extra overhead from calls to database queries.</p>
<p>This is even more apparent if you use the action helper, as the request is copied, and a new dispatch created (profile your code and see just how much overhead this involves, its a lot!).</p>
<h3>Unnecessary Complexity</h3>
<p>Trying to follow the application flow through an application which utilises the action stack adds a level of complexity which need not be there.</p>
<p>If you want to see what&#8217;s going on at a URL, you should be able to go to that action, and see which model methods are being invoked, and what is being passed to the view.</p>
<h3>Design Issues</h3>
<p>This is the biggest reason for not using the action stack. If you are using the action stack, you are almost certainly a long way from a true &#8220;MVC&#8221; design. The units of code you are using in your actions, probably belongs in the model.</p>
<p>Your model should encapsulate all the code to extract data, insert data, and manipulate objects, so all your controller action should include is a bunch of calls to the model to fetch data, or insert/update it, but in the form of single method calls only. remember you should be directing the data to the model, not manipulating it.</p>
<h2>Why it is good</h2>
<h3>Illusion of DRY coding</h3>
<p>The action stack can lead you into a false sense of security that your writing nice &#8220;DRY&#8221; code. You are in fact writing dry code, but usually in the wrong place, in fact, if your code is not abstracted into your model, it will end up no-longer being dry, as you will end up with two actions with overlapping functionality, and as such, overlapping code!</p>
<h2>The way forward</h2>
<h3>Fat Models, Thin Controllers</h3>
<p>Your controllers should be minimalist. they exist only to direct data, and to provide some interface to HTTP actions such as redirects.</p>
<p>The bulk of the code in your application should be in your model. For example, if you are writing a blog application, and the action you are writing produces a list of posts. This should require in the action, nothing more than a call to $model-&gt;getPosts(); possibly passing one or more paramaters from the URL (such as year and month) as parameters to the method.</p>
<p>This not only allows you to do away with the action stack, but also allows your code to be portable throughout the application, in true DRY style.</p>
<p>There is an upcomming book, which has a very good overview of how these kinds of models should be written. You can read it <a title="The Zend Framework and Writing Models" href="http://www.survivethedeepend.com/zendframeworkbook/en/1.0/the.model">here</a></p>
<h3>View Helpers</h3>
<p>View helpers can be useful for items which you frequently need, or for items which are simply too small to justify writing a whole view script for them. there is a good example in the <a title="Writing a view helper to replace an action() call" href="http://framework.zend.com/manual/en/performance.view.html#performance.view.action.model">performance guide</a>.</p>
<p>When you want to perform some logic before rendering a view script, a view helper can also be useful to help keep your layout or view free of large switches or if statements. For example this can be something like rendering a login form when a user is not logged in (which would require no view script, only a Zend_Form object), and a menu when they are, or be useful to set up some context for a view partial before rendering it, so that your controller does not have to pass a variable to the view when it would be some default value.</p>
<h3>(Partial) Views</h3>
<p>Partial views do the leg work of replacing the actionstack. In your partial views, you should call read-only methods of the model, to build items such as menus. this could be something like $model-&gt;getSideBarMenuItems(); which would return a dataset to loop through and render.</p>
<h2>Some other notes</h2>
<p>There has been an issue raised in the Zend Framework JIRA (<a title="Zend Framework Jira Issue tracker" href="http://framework.zend.com/issues/browse/ZF-5840">ZF-5840</a>) with regard to removing the action view helper for ZF version 2.0. This is somewhere you may wish to post your opinion on this subject (keep it specific!), or vote to have it removed <img src='http://www.rmauger.co.uk/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rmauger.co.uk/2009/03/why-the-zend-framework-actionstack-is-evil/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>My first Zend Framework proposal is now in incubator!</title>
		<link>http://www.rmauger.co.uk/2009/01/my-first-zend-framework-proposal-is-now-in-incubator/</link>
		<comments>http://www.rmauger.co.uk/2009/01/my-first-zend-framework-proposal-is-now-in-incubator/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 20:57:17 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[Proposal]]></category>
		<category><![CDATA[validator]]></category>
		<category><![CDATA[Validators]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.rmauger.co.uk/?p=16</guid>
		<description><![CDATA[My previous post was all about my proposal for a database lookup validator for Zend Framework. This proposal has now been accepted and is available in the incubator. During the process of refining the proposal, Ralph Schindler suggested renameing the validator, and splitting it in two, to make it as verbose as possible (i.e. the [...]]]></description>
			<content:encoded><![CDATA[<p>My previous post was all about my proposal for a database lookup validator for Zend Framework.</p>
<p><span id="more-16"></span></p>
<p>This proposal has now been accepted and is available in the incubator.</p>
<p>During the process of refining the proposal, Ralph Schindler suggested renameing the validator, and splitting it in two, to make it as verbose as possible (i.e. the name says exactly what it does). So, an abstract class has been added, and the DbMatch name dropped. The validators are  now called Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists. check the <a title="Check a user does not already exist with Zend Framework" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Validate_Db_RecordExists+-+Zend_Validate_Db_NoRecordExists+-+Ryan+Mauger">wiki page</a> for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rmauger.co.uk/2009/01/my-first-zend-framework-proposal-is-now-in-incubator/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Zend Framework component proposal &#8211; Zend_Validate_DbMatch</title>
		<link>http://www.rmauger.co.uk/2008/10/zend-framework-component-proposal-zend_validate_dbmatch/</link>
		<comments>http://www.rmauger.co.uk/2008/10/zend-framework-component-proposal-zend_validate_dbmatch/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 20:39:41 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Proposal]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Validate_DbMatch]]></category>

		<guid isPermaLink="false">http://www.rmauger.co.uk/?p=14</guid>
		<description><![CDATA[After seeing validators for checking if a value exists in a database table for about the tenth time on IRC, i have decided to put up a proposal for Zend_Validate_DbMatch. The code i have proposed should allow you to check if a value exists in a given field of a given table, and be easy [...]]]></description>
			<content:encoded><![CDATA[<p>After seeing validators for checking if a value exists in a database table for about the tenth time on IRC, i have decided to put up a proposal for Zend_Validate_DbMatch.</p>
<p><span id="more-14"></span></p>
<p>The code i have proposed should allow you to check if a value exists in a given field of a given table, and be easy to attach to your forms.</p>
<p>If you want to see this in the Zend Framework, or want to see the source see the proposals page in the <a title="Zend Framework Wiki" href="http://framework.zend.com/wiki/">ZF Wiki</a>.</p>
<p>You can find the <a title="Zend_Validate_DbMatch" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Validate_DbMatch+-+Ryan+Mauger">Zend_Validate_DbMatch</a> proposal in full <a title="Zend_Validate_DbMatch proposal" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Validate_DbMatch+-+Ryan+Mauger">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rmauger.co.uk/2008/10/zend-framework-component-proposal-zend_validate_dbmatch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

