<?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>Rob Allen&#039;s DevNotes</title>
	<atom:link href="http://akrabat.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://akrabat.com</link>
	<description>Developing PHP software in the Real World, by Rob Allen</description>
	<lastBuildDate>Fri, 11 May 2012 12:52:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Evan Coury: Module-specific layouts in Zend Framework 2</title>
		<link>http://akrabat.com/around-the-web/evan-coury-module-specific-layouts-in-zend-framework-2/</link>
		<comments>http://akrabat.com/around-the-web/evan-coury-module-specific-layouts-in-zend-framework-2/#comments</comments>
		<pubDate>Fri, 11 May 2012 11:11:59 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Around the web]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2338</guid>
		<description><![CDATA[Evan Coury has posted Module-specific layouts in Zend Framework 2 First, I should point out that the title of this post is a bit of an intentional misnomer. There’s really no such thing as “module-specific” anything in ZF2, so what we’re really talking about is the topmost namespace of the controller being dispatched. So in [...]]]></description>
			<content:encoded><![CDATA[<p>Evan Coury has posted <a href="http://blog.evan.pro/module-specific-layouts-in-zend-framework-2">Module-specific layouts in Zend Framework 2</a></p>
<blockquote><p>First, I should point out that the title of this post is a bit of an intentional misnomer. There’s really no such thing as “module-specific” anything in ZF2, so what we’re really talking about is the topmost namespace of the controller being dispatched. So in the case of MyModule\Controller\SomeController, the topmost namespace would be MyModle. In most cases, this will be the name of a given module.</p>
<p>Here’s how you can easily switch the layout (or perform any other arbitrary logic) for a specific module in Zend Framework 2.0 (as of d0b1dbc92)</p></blockquote>
<p>He shows how easy it is to register an event that is only triggered when an action belonging to the namespace of the current module is dispatched. If you need to change the layout for a given module, this is the best way to do it as of today.</p>
<p>His point that a Module is merely the namespace of the dispatch controller is very important to understand too!</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2338&amp;md5=a6a29d12d62eec6fd45e782354db2077" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/around-the-web/evan-coury-module-specific-layouts-in-zend-framework-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Faround-the-web%2Fevan-coury-module-specific-layouts-in-zend-framework-2%2F&amp;language=en_GB&amp;category=text&amp;title=Evan+Coury%3A+Module-specific+layouts+in+Zend+Framework+2&amp;description=Evan+Coury+has+posted+Module-specific+layouts+in+Zend+Framework+2+First%2C+I+should+point+out+that+the+title+of+this+post+is+a+bit+of+an+intentional+misnomer.+There%E2%80%99s+really...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Vagrant in Zend Framework 1</title>
		<link>http://akrabat.com/zend-framework/vagrant-in-zf1-trunk/</link>
		<comments>http://akrabat.com/zend-framework/vagrant-in-zf1-trunk/#comments</comments>
		<pubDate>Wed, 09 May 2012 07:12:34 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2324</guid>
		<description><![CDATA[I recently added support for vagrant to the Zend Framework codebase to enable easier testing. I was motivated by some work the joind.in folks have done to get a working development environment for joind.in development using Vagrant. Vagrant is a fantastic tool that enables you to manage and run virtual machines from the command line, [...]]]></description>
			<content:encoded><![CDATA[<p>I recently added support for <a href="http://vagrantup.com/">vagrant</a> to the Zend Framework codebase to enable easier testing. I was motivated by some work the <a href="https://joind.in">joind.in</a> folks have done to get a working development environment for joind.in development using Vagrant.</p>
<p>Vagrant is a fantastic tool that enables you to manage and run virtual machines from the command line, including automatic provisioning of them using <a href="http://puppetlabs.com/">puppet</a> or <a href="http://www.opscode.com/chef/">chef</a>.  The really cool thing about it however from my point of view is that vagrant automatically sets up the VM with a folder called /vagrant that holds the code on your local hard drive from where you started the VM. This means that you can continue to edit your code in your local editor/IDE and test it within the VM easily.</p>
<p>I highly recommend checking it out.</p>
<h3>ZF1's Vagrant set up</h3>
<p>The Vagrant set up for ZF1 is designed for testing ZF1 against multiple PHP versions. As such it sets up a simple Ubuntu VM with the required toolchain for compiling PHP and provides a script called <tt>php-build.sh</tt> which will download and build any PHP 5.2, 5.3 or 5.4 version that you are interested in. I based this script on information in Derick Rethans' excellent <a href="http://derickrethans.nl/multiple-php-version-setup.html">Multiple PHP versions set-up</a> article. </p>
<p>One thing that I discovered was that by default, the VM cannot create symlinks in <tt>/vagrant</tt>. The way to solve this is to add the following to the <tt>Vagrantfile</tt>:</p>
<pre>
  config.vm.customize [
    "setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/v-root", "1"
  ]
</pre>
<p>I chose to use puppet to install the required packages and created a simple <a href="http://framework.zend.com/svn/framework/standard/trunk/puppet/manifests/default.pp">default.pp</a> configuration. I'm sure this isn't optimal, but it works :) </p>
<h3>Running ZF1 unit tests</h3>
<p>The process to set up ZF1 to run unit tests in a VM using PHPUnit 3.4, follow these steps:</p>
<p><em>1. Install requirements for running the VM:</em></p>
<ul>
<li>VirtualBox (<a href="https://www.virtualbox.org/">https://www.virtualbox.org/</a>)</li>
<li>Ruby (<a href="http://www.ruby-lang.org/">http://www.ruby-lang.org/</a>)</li>
<li>Vagrant (<a href="http://vagrantup.com/">http://vagrantup.com/</a>)</li>
</ul>
<p><em>2. Checkout the ZF1 repository:</em></p>
<pre>
    $ svn checkout http://framework.zend.com/svn/framework/standard/trunk zf1-dev
    $ cd zf1-dev
</pre>
<p><em>3. Start the process by running Vagrant.</em></p>
<pre>
    $ vagrant up
</pre>
<p>This will take a long while as it has to download a VM image and then provision it. Once it has finished, it will exit and leave you back at the command prompt. </p>
<p><em>4. SSH into the VM</em></p>
<pre>
    $ vagrant ssh
</pre>
<p>Vagrant sets up key-less ssh connections to the VM that "just works" :)</p>
<p><em>5. Build a version of PHP.</em></p>
<pre>
    $ php-build.sh 5.3.11
</pre>
<p>This also takes a while as it compiles PHP for you! It also installs PHPUnit 3.4 as that's the version we need to unit test ZF1. </p>
<p>Each version of PHP that you compile is stored in /usr/local/php/{version number}. You can compile any version; I have 5.2.4, 5.2.12, 5.3.3 and 5.3.11 installed at the moment…</p>
<p><em>6. Select PHP to use:</em></p>
<pre>
   $ pe 5.3.11
</pre>
<p><tt>pe</tt> is a handy shell function that Derick wrote that changes your PHP environment to whichever version your specify.</p>
<p><em>7. Run tests</em></p>
<pre>
   $ cd /vagrant/tests
   $ php runtests.php
</pre>
<p>Alternatively, you can run each component's tests individually:</p>
<pre>
   $ phpunit --stderr -d memory_limit=-1 Zend/Acl/AclTest.php
   $ phpunit --stderr -d memory_limit=-1 Zend/Amf/AllTests.php
   (etc...)
</pre>
<p>Obviously, you repeat steps 5 through 7 for each version of PHP you want to test on.</p>
<p>To stop your Vagrant VM, exit the SSH shell and type `vagrant halt` or `vagrant suspend`. For more details on controlling your Vagrant VM, I recommend <a href="http://www.lornajane.net/posts/2012/using-an-existing-vagrant-setup-for-php-development">Lorna's article</a></p>
<p>Running unit tests on Zend Framework 1 is now considerably easier!</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2324&amp;md5=0987707112a96caf9810d1494847d728" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework/vagrant-in-zf1-trunk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework%2Fvagrant-in-zf1-trunk%2F&amp;language=en_GB&amp;category=text&amp;title=Vagrant+in+Zend+Framework+1&amp;description=I+recently+added+support+for+vagrant+to+the+Zend+Framework+codebase+to+enable+easier+testing.+I+was+motivated+by+some+work+the+joind.in+folks+have+done+to+get+a+working...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Unit testing Zend Framework 1</title>
		<link>http://akrabat.com/zend-framework/unit-testing-zend-framework-1/</link>
		<comments>http://akrabat.com/zend-framework/unit-testing-zend-framework-1/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 10:33:50 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2320</guid>
		<description><![CDATA[As part of our release process for Zend Framework 1.12, I've been working through the unit tests and running them on PHP 5.2.4 as it seems that recent changes weren't being tested with that version. This isn't totally surprising as Open Source contributors are, almost by definition, interested in new things and so are much [...]]]></description>
			<content:encoded><![CDATA[<p>As part of our release process for Zend Framework 1.12, I've been working through the unit tests and running them on PHP 5.2.4 as it seems that recent changes weren't being tested with that version. This isn't totally surprising as Open Source contributors are, almost by definition, interested in new things and so are much more likely to be running PHP 5.4 rather than 5.2! This is, of course, a compelling reason for using continuous integration and I'm quite excited with <a href="http://travis-ci.org/">Travis-CI</a> and we are using it with ZF2.</p>
<h3>Installing PHPUnit 3.4</h3>
<p>The first challenge that I encountered was that ZF1's unit test are not compatible with PHPUnit 3.6. As there are over 14,000 ZF1 unit tests which have been written since 2006, there hasn't been much enthusiasm for rewriting them to be PHPUnit 3.6 compatible. (However, if someone wants to volunteer, please contact me!)</p>
<p>As I have PHPUnit 3.6 installed for testing other projects, I needed to install PHPUnit 3.4 side-by-side with version 3.6 This turns out to be relatively easy and has been documented by Christer Edvartsen in his article <a href="http://tech.vg.no/2011/11/29/running-multiple-versions-of-phpunit/">Running Multiple Versions of PHPUnit</a>.</p>
<p>I ran into one problem with his instructions though and needed this code to be added to the top of <tt>phpunit</tt>:</p>
<pre class="phpcode"><span style="color: #0000BB">set_include_path</span><span style="color: #007700">(</span><span style="color: #0000BB">implode</span><span style="color: #007700">(</span><span style="color: #0000BB">PATH_SEPARATOR</span><span style="color: #007700">,&nbsp;array(
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">__DIR__&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #DD0000">'/../share/php'</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'/usr/share/php'</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">get_include_path</span><span style="color: #007700">()
)));</span>
</span></code></pre>
<p>Having done this though, PHPUnit 3.4 works correctly and we can run ZF1 unit tests.</p>
<h3>Running the ZF1 unit tests</h3>
<p>To run ZF1's unit tests, you first need to check out the code from the <a href="http://framework.zend.com/svn/framework/standard/trunk/">Subversion repository</a>.  </p>
<pre>svn co http://framework.zend.com/svn/framework/standard/trunk/</pre>
<p>Due to the number of tests and the memory that they take up, you should run tests for each component individually.</p>
<p>The command to use is:</p>
<pre>phpunit34 --stderr -d memory_limit=-1 Zend/{Component}/AllTests.php</pre>
<p>Note:</p>
<ul>
<li><tt>--stderr</tt> pipes PHPUnit's output to stderr which means that any tests that rely on <tt>header()</tt> will work. (i,e. don't test <tt>Zend_Session</tt> without it!)</li>
<li><tt>-d memory_limit=-1</tt> will turn off PHP's memory_limit setting. The ZF1 unit tests use a lot of memory, so this is easiest.</li>
<li>The tests <em>rely</em> on being set up correctly. This is done using <tt>AllTests.php</tt> so don't forget this. Tests will fail if you forget!</li>
</ul>
<p>All that needs to happen now is that any failing tests are fixed!</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2320&amp;md5=612fa1861d4dbd0aa3f4c2bfcb2a9ba0" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework/unit-testing-zend-framework-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework%2Funit-testing-zend-framework-1%2F&amp;language=en_GB&amp;category=text&amp;title=Unit+testing+Zend+Framework+1&amp;description=As+part+of+our+release+process+for+Zend+Framework+1.12%2C+I%27ve+been+working+through+the+unit+tests+and+running+them+on+PHP+5.2.4+as+it+seems+that+recent+changes+weren%27t...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Evan Coury: Sharing a database connection across modules in Zend Framework 2</title>
		<link>http://akrabat.com/around-the-web/evan-coury-sharing-a-database-connection-across-modules-in-zend-framework-2/</link>
		<comments>http://akrabat.com/around-the-web/evan-coury-sharing-a-database-connection-across-modules-in-zend-framework-2/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 07:42:40 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Around the web]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2316</guid>
		<description><![CDATA[Evan Coury has posted Sharing a database connection across modules in Zend Framework 2 &#187; Evan's Blog With the new modular infrastructure in Zend Framework 2, one of the most common questions will indoubitably be how to share a database connection across modules. Here’s a quick explanation of how to share your database connection across [...]]]></description>
			<content:encoded><![CDATA[<p>Evan Coury has posted <a href="http://blog.evan.pro/sharing-a-database-connection-across-modules-in-zend-framework-2">Sharing a database connection across modules in Zend Framework 2 &raquo; Evan's Blog</a></p>
<blockquote><p>With the new modular infrastructure in Zend Framework 2, one of the most common questions will indoubitably be how to share a database connection across modules. Here’s a quick explanation of how to share your database connection across multiple modules in a way that can even allow you to use a single connection between Zend\Db, Doctrine2, and possibly even other database libraries / ORMs.</p></blockquote>
<p>If you're using ZF2, this is a <em>must-read</em>.</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2316&amp;md5=5fc6d4d63f42a3f0997f0aa601997d44" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/around-the-web/evan-coury-sharing-a-database-connection-across-modules-in-zend-framework-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Faround-the-web%2Fevan-coury-sharing-a-database-connection-across-modules-in-zend-framework-2%2F&amp;language=en_GB&amp;category=text&amp;title=Evan+Coury%3A+Sharing+a+database+connection+across+modules+in+Zend+Framework+2&amp;description=Evan+Coury+has+posted+Sharing+a+database+connection+across+modules+in+Zend+Framework+2+%26raquo%3B+Evan%27s+Blog+With+the+new+modular+infrastructure+in+Zend+Framework+2%2C+one+of+the+most...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>An introduction to Zend\EventManager</title>
		<link>http://akrabat.com/zend-framework-2/an-introduction-to-zendeventmanager/</link>
		<comments>http://akrabat.com/zend-framework-2/an-introduction-to-zendeventmanager/#comments</comments>
		<pubDate>Mon, 23 Apr 2012 09:55:31 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework 2]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2307</guid>
		<description><![CDATA[Zend Framework 2's EventManager is a key component of the framework which is used for the core MVC system. The EventManager allows a class to publish events that other objects can listen for and then act when the event occurs. The convention within Zend Framework 2 is that any class that triggers events composing its [...]]]></description>
			<content:encoded><![CDATA[<p>Zend Framework 2's <tt>EventManager</tt> is a key component of the framework which is used for the core MVC system. The EventManager allows a class to publish events that other objects can listen for and then act when the event occurs. The convention within Zend Framework 2 is that any class that triggers events composing its own EventManager.</p>
<h3>Terminology</h3>
<p>For the purposes of this article, we will use these definitions:</p>
<ul>
<li>An <strong>EventManager</strong> is an object that holds a collection of listeners for one or more named events, and which triggers events.
</li>
<li>An <strong>event</strong> is an action that is triggered by an EventManager.</li>
<li>A <strong>listener</strong> is a callback that can react to an event.</li>
</ul>
<p>When the <tt>EventManager</tt>'s <tt>trigger()</tt> method is called, all the listeners attached to the event are called in turn and are passed an <tt>Event</tt> object which contains a target and additional parameters as required.</p>
<h3>Triggering events</h3>
<p>A typical use-case for <tt>EventManager</tt> is to trigger events within a mapper class:</p>
<pre class="phpcode"><span style="color: #0000BB">
</span><span style="color: #007700">use&nbsp;</span><span style="color: #0000BB">Zend</span><span style="color: #007700">\</span><span style="color: #0000BB">EventManager</span><span style="color: #007700">\</span><span style="color: #0000BB">EventManager</span><span style="color: #007700">;
use&nbsp;</span><span style="color: #0000BB">Zend</span><span style="color: #007700">\</span><span style="color: #0000BB">EventManager</span><span style="color: #007700">\</span><span style="color: #0000BB">Event</span><span style="color: #007700">;

class&nbsp;</span><span style="color: #0000BB">PhotoMapper
</span><span style="color: #007700">{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;</span><span style="color: #0000BB">$events</span><span style="color: #007700">;

&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">events</span><span style="color: #007700">()&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events&nbsp;</span><span style="color: #007700">=&nbsp;new&nbsp;</span><span style="color: #0000BB">EventManager</span><span style="color: #007700">(</span><span style="color: #0000BB">__CLASS__</span><span style="color: #007700">);&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;</span><span style="color: #0000BB">$events</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">findById</span><span style="color: #007700">(</span><span style="color: #0000BB">$id</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">trigger</span><span style="color: #007700">(</span><span style="color: #0000BB">__FUNCTION__&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #DD0000">'.pre'</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(</span><span style="color: #DD0000">'id'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">$id</span><span style="color: #007700">));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;retrieve&nbsp;from&nbsp;database&nbsp;and&nbsp;create&nbsp;a&nbsp;$photo&nbsp;entity&nbsp;object

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">trigger</span><span style="color: #007700">(</span><span style="color: #0000BB">__FUNCTION__&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #DD0000">'.post'</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">,&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(</span><span style="color: #DD0000">'photo'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">$photo</span><span style="color: #007700">));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;</span><span style="color: #0000BB">$photo</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;&nbsp;class&nbsp;continues...
</span>
</span></code></pre>
<p>Firstly, note that, by convention, the <tt>EventManager</tt> instance is called <tt>$events</tt> and we use a method called <tt>events()</tt> and that will instantiate the <tt>EventManager</tt> for us when needed. This is a very common code pattern in ZF2 classes; so common in fact that the <tt><a href="https://github.com/ZF-Commons/ZfcBase">ZfcBase</a></tt> module contains a class called <tt>ZfcBase\EventManager\EventProvider</tt> that you can extend from to provide you with this functionality.</p>
<p>Within our mapper's <tt>findById()</tt>method, we trigger two events: before and after the actual work is done. When triggering an event, we supply the event's name, the target class and an array of data that the listeners may be interested in.</p>
<p>By convention, we use the name of the method as our event's name. This makes it predictable for users of the class. Also, by convention, if there two events, then we append '.pre' and '.post' to the event name. the target class is usually the class that triggered the event, and so we pass in <tt>$this</tt>. Finally, we can provide some additional data to the listeners. In this particular method, we supply the <tt>id</tt> before we retrieve (as that's all we have!) After retrieval, we have the entity object itself, so we supply that to the listener callbacks.</p>
<h3>Listening for an event</h3>
<p>A listener is just any PHP callback function which takes a single argument, <tt>$event</tt>, which is an instance of an <tt>Event</tt>. The listener is attached using event manager's <tt>attach()</tt> method. For example, we could attach a logger to our mapper's <tt>findById.pre</tt> event like this:</p>
<pre class="phpcode"><span style="color: #0000BB">
$photoMapper</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">attach</span><span style="color: #007700">(</span><span style="color: #DD0000">'findById.pre'</span><span style="color: #007700">,&nbsp;function(</span><span style="color: #0000BB">Event&nbsp;$event</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$message&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #DD0000">"Trying&nbsp;to&nbsp;retrieve&nbsp;photo:&nbsp;"&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #0000BB">$event</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'id'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">MyLogger</span><span style="color: #007700">::</span><span style="color: #0000BB">log</span><span style="color: #007700">(</span><span style="color: #0000BB">$message</span><span style="color: #007700">);
});
</span>
</span></code></pre>
<p>The <tt>$event</tt> parameter that is passed to the listener method has three user methods:</p>
<ul>
<li><tt>getName()</tt> - Useful when the same listener is attached to multiple events</li>
<li><tt>getTarget()</tt> - Usually the class that trigger the event</li>
<li><tt>getParams()</tt> - Retrieve the parameters sent when the event was triggered.</li>
</ul>
<p><strong>Priority</strong><br />
When attaching a listener to an event, you can specify the priority in the third parameter. The larger the number, the earlier the listener is called. i.e. for a listener that you want to be executed first, set the priority to say 1000. For a listener that you want to be executed last, set the priority the -1000. The default priority is 1 and listeners with the same priority are executed in order or priority. </p>
<h3>Short circuiting</h3>
<p>The return value from <tt>trigger()</tt> is a <tt>ResponseCollection</tt> which is a collection of all the returned results from every listener that has been called in reverse order. i.e. the result from the last listener is first in the collection.</p>
<p>As this result is passed back to trigger, we can use it to stop processing of the listeners if something interesting happens. This is known as short-circuiting and we do this by attaching a callback as the last parameter to <tt>trigger()</tt>.</p>
<p>A good example of this is a caching solution on our <tt>findById()</tt> method. We change it so that it looks like this:</p>
<pre class="phpcode"><span style="color: #0000BB">
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">public&nbsp;function&nbsp;</span><span style="color: #0000BB">findById</span><span style="color: #007700">(</span><span style="color: #0000BB">$id</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$results&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">trigger</span><span style="color: #007700">(</span><span style="color: #0000BB">__FUNCTION__&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #DD0000">'.pre'</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">,&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(</span><span style="color: #DD0000">'id'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">$id</span><span style="color: #007700">),
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;function&nbsp;(</span><span style="color: #0000BB">$result</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;(</span><span style="color: #0000BB">$result&nbsp;</span><span style="color: #007700">instanceof&nbsp;</span><span style="color: #0000BB">Photo</span><span style="color: #007700">)&nbsp;?&nbsp;</span><span style="color: #0000BB">true&nbsp;</span><span style="color: #007700">:&nbsp;</span><span style="color: #0000BB">false</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(</span><span style="color: #0000BB">$results</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">stopped</span><span style="color: #007700">())&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;we&nbsp;ended&nbsp;early.&nbsp;Result&nbsp;returned&nbsp;from&nbsp;last&nbsp;listener&nbsp;was&nbsp;an&nbsp;entity
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$photo&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$results</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">last</span><span style="color: #007700">();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;</span><span style="color: #0000BB">$photo</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;retrieve&nbsp;from&nbsp;database&nbsp;and&nbsp;create&nbsp;a&nbsp;$photo&nbsp;entity&nbsp;object

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">trigger</span><span style="color: #007700">(</span><span style="color: #0000BB">__FUNCTION__&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #DD0000">'.post'</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(</span><span style="color: #DD0000">'photo'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">$photo</span><span style="color: #007700">));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;save&nbsp;$photo&nbsp;to&nbsp;cache&nbsp;here

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">return&nbsp;</span><span style="color: #0000BB">$photo</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}
</span>
</span></code></pre>
<p>We have added a callback to our <tt>trigger()</tt> call that returns <tt>true</tt> if the result returned by a listener is an instance of <tt>Photo</tt>. This means that we can attach a listener that tries to read a cache for the <tt>id</tt>. If it finds one, then it returns the cached object. The trigger callback notices and returns true and the <tt>ResponseCollection</tt>'s <tt>stopped</tt> flag is set to true.</p>
<p>We then test for <tt>stopped()</tt> and if it has been set, <tt>$results->last()</tt> contains the <tt>Photo</tt> entity that we need.</p>
<h3>SharedEventManager</h3>
<p>It's common that you may want to set up listeners before the objects with the event manager you need has been instantiated. Good examples are listeners that log or cache. ZF2 comes with the concept of the <tt>SharedEventManager</tt>. Essentially you attach listeners to the <tt>SharedEventManager</tt> and then when the particular event manager's <tt>trigger()</tt> is called, it will also call all the listeners attached to the shared event collection.</p>
<p>There are two ways to access the <tt>SharedEventManager</tt>: DIC injection into the object where you need it or via a static class called (rather unimaginatively) <tt>StaticEventManager</tt>. The exact details of how the injection will work are up in the air at the moment as it's expected that some additional defaults will be provided to make it easier in beta 4 and the use of the <tt>StaticEventManager</tt> will become deprecated.</p>
<p>In either case, the way to attach a listener to the <tt>SharedEventManager</tt> is the same:</p>
<pre class="phpcode"><span style="color: #0000BB">
</span><span style="color: #FF8000">//&nbsp;$events&nbsp;is&nbsp;a&nbsp;Zend\EventManager\SharedEventManager&nbsp;instance&nbsp;either&nbsp;injected
//&nbsp;or&nbsp;acquired&nbsp;using&nbsp;$events&nbsp;=&nbsp;StaticEventManager::getInstance();

</span><span style="color: #0000BB">$events</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">attach</span><span style="color: #007700">(</span><span style="color: #DD0000">'Gallery\Model\PhotoMapper'</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'findById.pre'</span><span style="color: #007700">,&nbsp;function(</span><span style="color: #0000BB">Event&nbsp;$event</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$message&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #DD0000">"Trying&nbsp;to&nbsp;retrieve&nbsp;photo:&nbsp;"&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #0000BB">$event</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'id'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">MyLogger</span><span style="color: #007700">::</span><span style="color: #0000BB">log</span><span style="color: #007700">(</span><span style="color: #0000BB">$message</span><span style="color: #007700">);
});
</span>
</span></code></pre>
<p>Note that the only change to the <tt>attach</tt> call is the addition of a new first parameter which is the name of the class where the event manager is to be found. In this case, it's <tt>Gallery\Model\PhotoMapper</tt>. The other three parameters are the same: event name, callback and priority.</p>
<p>In terms of execution of listeners with the same priority, those attached directly are executed before those attached via the <tt>SharedEventManager</tt>.</p>
<h3>Summary</h3>
<p>This article covers how to use the <tt>EventManager</tt> in your application. The biggest advantage to using <tt>EventManager</tt> in your application is that you can decouple classes that really shouldn't be coupled together which makes your code easier to write and maintain. In fact, this is so useful, that ZF2's MVC system makes heavy use of <tt>EventManager</tt>; The module manager, routing, dispatching and the view layer are all implemented using listeners attached to events.</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2307&amp;md5=0a829ab47cf5765812d6187421eab25f" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework-2/an-introduction-to-zendeventmanager/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Fan-introduction-to-zendeventmanager%2F&amp;language=en_GB&amp;category=text&amp;title=An+introduction+to+Zend%5CEventManager&amp;description=Zend+Framework+2%27s+EventManager+is+a+key+component+of+the+framework+which+is+used+for+the+core+MVC+system.+The+EventManager+allows+a+class+to+publish+events+that+other+objects...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Getting started with Natural Load Testing</title>
		<link>http://akrabat.com/review/getting-started-with-natural-load-testing/</link>
		<comments>http://akrabat.com/review/getting-started-with-natural-load-testing/#comments</comments>
		<pubDate>Wed, 04 Apr 2012 13:40:06 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Review]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2218</guid>
		<description><![CDATA[I've been following the products of WonderNetwork for a while as they do some interesting stuff with servers around the world. I particularly like Wonder VPN as a drop dead simple and reliable VPN is very handy for any mobile user who wants some security when using a wireless network in Starbucks! Recently they have [...]]]></description>
			<content:encoded><![CDATA[<p>I've been following the products of <a href="https://wondernetwork.com/">WonderNetwork</a> for a while as they do some interesting stuff with servers around the world. I particularly like <a href="https://wonderproxy.com/signup/vpn">Wonder VPN</a> as a drop dead simple and reliable VPN is very handy for any mobile user who wants some security when using a wireless network in Starbucks! </p>
<p>Recently they have been working on a new product called <a href="https://load.wondernetwork.com">Natural Load Testing</a> which is intended to make load testing your web application very simple. It's a very friendly service which is immediately apparent on the home page where it says "not logged in, no greeting. how sad". It's a little touch that appeals to me.</p>
<p>Natural Load Testing is currently in private beta and the WonderNetwork guys invited me into the beta and have been generous enough to spend a small part of their marketing budget to enable me to be able to publish this article. They've even managed to cope with my list of complaints and still talk to me! In this tutorial I will walk through how to use the Natural Load Testing product (as is today) to get some results. Interpreting the results and improving your website and server infrastructure is your job though :)</p>
<h3>Getting Started</h3>
<p>Natural Load Testing (shortened to NLT in this article!) consists of 4 main areas where you interact with it:</p>
<ul>
<li>Creating tests</li>
<li>Configuring test suites</li>
<li>Running test suites</li>
<li>Reviewing results</li>
</ul>
<p>Upon log in, the home page consists of a set of friendly buttons:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT1.png" alt="Natural Load Testing home page" border="0" width="600" height="341" /></p>
<p>We start at the beginning: creating tests.</p>
<h3>Creating tests</h3>
<p>When load testing you need to configure your testing tool with the URLs of the pages and resources the you want to be tested. Natural Load Testing makes this job trivial by cleverly leveraging their proxy technology. By configuring your browser to use the NLT proxy, it will record every page you visit and provide you with a list of URLs which you can then use to create tests.</p>
<p>Obviously, as load testing involves hitting the server with a lot of requests, by the time NLT is out of beta, you will need to authorise each domain that you want to use. This is done in the "Manage Authorised Domains" section.</p>
<p>There is a helpful page on the NLT site that explains how to do this. Don't forget to turn off the proxy after recording. The WonderNetwork people have also remembered that you may want to record HTTPS traffic for load testing, and have provided a root certificate that you'll need to install. Again, there's help available on how to install this.</p>
<p>Once you have recorded some URLs, you can then click on the "Create" button and you are presented with a list of the most recent URLs you have recorded. </p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT2.png" alt="Recorded URLS" border="0" width="600" height="532" /></p>
<p>To create the test, you select the URLs that you require to be included (the checkbox in the header selects all within the group, which is very handy!). You then choose a name that will help you remember what this test does and create the test.</p>
<p>In order to create some interesting load tests on our site, I created a good few tests which I could then group into test suites.</p>
<h3>Configuring test suites</h3>
<p>Your tests are grouped into suites that are then run either sequentially or as a set of random loads. To create a suite, you click on the "Configure" button which then shows you the list of the suites that you have already created. </p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT3.png" alt="Test suites" border="0" width="600" height="502" /></p>
<p>In this screenshot you can see two test suites that I've created. The second test "ZF2 Tutorial only" is the simplest suite possible as it contains a single page load within a single step. The top suite shows a more complex suite which hints at the complexity of the suites that you can create. </p>
<p>A suite is composed of one or more steps which are run in sequence. Each step can have multiple tests. If there are multiple test in the same step, then NLT will randomly pick one test for each run.<br />
In this suite I have four tests in step 1 which are a set of pages within the BRI website. Step 2 is the contact page and so this test suite is measuring visiting one of 4 pages within the site and then choosing to go to the contact page. </p>
<p>Creation of a new test suite is done via drag and drop:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT4.png" alt="Create new test suite" border="0" width="600" height="400" /></p>
<p>You simply drag your green tests over to the list of steps on the right hand side. It's all quite easy. Rather weirdly, you can't reuse the same test in multiple steps, so if you're testing a cycle, then you need to duplicate the same test so that you can place it into two different steps. I haven't found a way to edit the steps within a test suite once created either, so make sure you get it right!</p>
<p>Once you have added tests to steps, you can then tell NLT to send data whilst load testing. This is useful for filling in forms or logging into the website, for instance. I haven't used this section as I haven't yet tested any pages with forms or requiring login.</p>
<p>Rather useful fully, you can change the domain that a test suite uses. This enables you to duplicate a test suite and then change the domain to test domain that's running on another server or using a different configuration which makes side-by-side testing a little easier.</p>
<h4>Calibration</h4>
<p>Once we have created a test suite, the next step is to calibrate it. NLT will not allow you to run a test suite before calibration, so don't forget this bit! Calibration is done from the test suites list page where there is a drop down box of operations you can do on each suite:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT5.png" alt="Operations on a test suite" border="0" width="600" height="181" /></p>
<p>Simply pick Calibrate and press Go. NLT will then perform a single run over your suite and present the standard results page. Ideally, I would like to see this page look different from the standard results page as it's a calibration run, not a standard test and so I was slightly confused at this point. Also, whilst the test is running, you simply see one of those "spinning gifs" to let you know that something is happening. I ran into a bug in this section which resulted in the calibration run failing, but I was never notified on the page that an error had occurred. </p>
<p>The calibration results on my ZF2 tutorial page suite look like this:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT6.png" alt="Calibration results" border="0" width="600" height="410" /></p>
<p>The intent of calibration is to provide a base-line to the NLT of the performance of the suite when there is no load. i.e. the idea is that this single run has provided an indication of the optimal conditions and we are expecting to be within 15% of this performance when testing under load. </p>
<h3>Running test suites</h3>
<p>Now that we have calibrated test suites, we can run some load tests and see what happens. In NLT parlance, we run test suites by pressing the Play button at which point the terminology changes to from play to execute. Simply select your test suite and press the Execute button. You are then presented with a form in order to set the run parameters:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT7.png" alt="Starting to execute a test" border="0" width="300" height="198" /></p>
<p>There are three parameters you need to set:</p>
<table>
<tr>
<th>Concurrent&nbsp;Users</th>
<td>How many users will hit your test suite. For steps with multiple tests, each user will randomly pick one to run.</td>
</tr>
<tr>
<th>Total Executions</th>
<td>How many times the suite will be run</td>
</tr>
<tr>
<th>Spin up Delay</th>
<td>Number of milliseconds before introducing the next user. A delay of 500 will results in 2 users per second being introduced to the load up to the total Concurrent users.</td>
</tr>
</table>
<p>We set these numbers up to create the required load testing profile. I've been using 100 users at 250ms spin-up for 2000 total executions as this takes around 30 to 60 seconds to complete a run and seems a reasonable profile for my blog given its traffic levels. </p>
<p>Upon pressing execute, NLT will spin up a number of worker processes on its servers and then display a graph that updates every few seconds showing you what happening:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT10.png" alt="Graphical results" border="0" width="600" height="297" /></p>
<p>As you can see in the screenshot above, you get this information:</p>
<ul>
<li>A bar showing number of active requests (blue) on top of number of requests initiated.</li>
<li>A line chart of median response time.</li>
</ul>
<p>The x-axis is in seconds. Hence the red bar chart shows the number of requests initiated during each second and the blue bar shows the number of requests that were still active at the end of the second. Hence a request that completed within a second is counted in the red bar, but not in the blue. Ideally, therefore we would like to see smaller blue bars than red bars and we definitely don't want to see blue bars getting bigger.</p>
<p>The green line shows us the average time it takes to server all requests in that second. Ideally, we want this number to be lower. Clearly, if there are any errors serving a request (e.g. an nginx bad gateway error), the rather fast failure time is not counted as it would bring the average down!</p>
<p>We can also view the data as a table:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT11.png" alt="Tabluar data" border="0" width="600" height="270" /></p>
<p>Obviously, this is right at the start of the run, and so all look good. Clicking on a given run id will provide us with more information. This is a run that's later in the test:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT12.png" alt="Detailed results" border="0" width="600" height="336" /></p>
<p>As you can see, the server was struggling now! The red background means that the request took more than 15% longer than the calibration run and the difference from calibration is shown in brackets in the Response Time column. In this particular run, the main HTML took 760ms to deliver which as 411ms longer than the calibration run. We're also struggling to serve images in a sensible time. This is clearly not ideal! </p>
<p>Looking at what's going on on the server whilst running a load test is also instructive. A good introduction to the server tools that are useful is <a href="http://h30565.www3.hp.com/t5/Feature-Articles/16-Linux-Server-Monitoring-Commands-You-Really-Need-To-Know/ba-p/1936">16 Linux server monitoring commands you really need to know</a> by Steven Vaughan-Nichols.</p>
<h3>Reviewing results</h3>
<p>Once you have a few runs under your belt, the Review page becomes useful. In this page we can see a list of all our previous runs and most importantly, we can edit the title of each run and give it a useful name. It would be nice to be able to store additional notes about each run though.</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLT14.png" alt="Previous runs" border="0" width="600" height="268" /></p>
<p>Adding the title makes it much easier to remember why a given run was performed and I've found it useful.</p>
<h3>Using Natural Load Testing to improve performance</h3>
<p>The obvious first target for testing NLT, was my blog at akrabat.com. This is a simple WordPress blog which recently moved to a new server. I haven't been particularly worried about performance and don't really expect to ever be slash-dotted (or is it <a href="http://www.wolerized.com/blog/slashcal-dotted">Cal-dotted</a>, nowadays!) any time soon.  </p>
<p>However, as I've done nothing to tune the system, this is a good time to see how it behaved. The first run produced these results:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLTp-1.png" alt="NLTp 1" border="0" width="600" height="250" /></p>
<p>This isn't good! The only good sign was that none of the 2000 runs actually resulted in an error. A median response time around 1.5 seconds didn't sound good and the maximum run time was 13 seconds!</p>
<p>Something had to be done!</p>
<p>A little bit of investigating showed that neither APC or WP Super Cache was installed on the server. So I turned them on.</p>
<p>The effect of APC can be seen here:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLTp-2.png" alt="NLTp 2" border="0" width="600" height="245" /></p>
<p>We now have an average response time of much less than 500ms which seems much saner. There were a number of very long requests of over 1 second though.</p>
<p>To see if I could improve this further, I then installed and enabled <a href="http://wordpress.org/extend/plugins/wp-super-cache/">WP Super Cache</a> in PHP mode and re-ran Natural Load Testing. The results were:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLTp-5.png" alt="NLTp 5" border="0" width="600" height="248" /></p>
<p>Note that you need to be careful when comparing graphs as the axes are automatically scaled. Looking at the results with WP Super Cache was enabled, I can see that the response time display of the graph is much smoother. The tabular data backs this up as it shows that the vast majority of requests were taking less than 200ms with significantly fewer runs taking much longer. Also, the curve of the number of requests initiated vs request active at the end of each second is much smoother, which indicates that with WP Super Cache enabled, the server should be able to hold its own over a longer time period much more easily.</p>
<p>I tested this hypothesis by doing 5000 runs rather than the 2000 shown above. The result was:</p>
<p><img src="http://akrabat.com/wp-content/uploads/2012-03-NLTp-6.png" alt="NLTp 6" border="0" width="600" height="241" /></p>
<p>Again, the median response time is nicely under 150ms for most of the time, but we have more variance in the response time, with a couple of seconds where the median was significantly over 250ms. </p>
<p>On the whole, my investigations with NLT have made my blog much more responsive and more likely to be able to handle more traffic than before I started this process.</p>
<h3>Other thoughts</h3>
<p>Having walked though what Natural Load Testing does, I also need to point out that when using it, you can tell that this is a product still in beta! Incidentally, the WonderNetwork people have responded to my reports quickly, even if half the time it was to let me know that my idea or complaint was already <a href="http://blog.preinheimer.com/index.php?/archives/376-User-Feedback,-the-endless-cycle.html">on their list</a>!</p>
<p>Nearly all the issues I have with NLT at the moment are related to usability, which I'm sure will be ironed out over time. My "favourite" annoyance as noted above is on the create test suite page where the Save button is above the section where you set up the suite's steps. If you accidentally press Save after entering a title, then you find you can't actually add any tests to the steps! There's also no menu bar or easy way to get from one section to another. You very quickly learn to click on the NLT logo at the top which takes you to the home page.</p>
<p>It would also be good if NLT would allow me to store "execution profiles" so that I don't have to keep typing in that I want 100 users for 2000 total runs.</p>
<p>I would also like to see more aggregate results. In particular, I'd like to have stats on the response time for say the 50th and 95th percentile. I'd also like to graph these against multiple runs along with the run title so I can see how the site's performance changed over time. This then leads to the idea that it would be nice if I could schedule a load test once a month at 3am local time!</p>
<h3>Conclusion</h3>
<p>Natural Load Testing is the first product I've used that makes me actually want to do load testing. It makes it easy to run a specific load test and repeat exactly the same test as frequently as you need to. Tweaking the server to see the effect that any given change has becomes an interesting task and your websites can only benefit as you reduce and remove the bottle necks that you find.</p>
<p>On the whole, I'm quite impressed with Natural Load Testing and can see that it could turn into a very useful tool in the web developer's toolbox.</p>
<p>As I mentioned at the top, NLT is currently in private beta. If you want to get an invite, head over to the <a href="https://load.wondernetwork.com/beta/please/">sign up form</a> and fill in your details. You also <em>have</em> to read the thank you for signing up message!</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2218&amp;md5=3ed01d3802a16f1ccd490b39d445a0f0" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/review/getting-started-with-natural-load-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Freview%2Fgetting-started-with-natural-load-testing%2F&amp;language=en_GB&amp;category=text&amp;title=Getting+started+with+Natural+Load+Testing&amp;description=I%27ve+been+following+the+products+of+WonderNetwork+for+a+while+as+they+do+some+interesting+stuff+with+servers+around+the+world.+I+particularly+like+Wonder+VPN+as+a+drop+dead...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Access view variables in another view model</title>
		<link>http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/</link>
		<comments>http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 12:15:31 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework 2]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2253</guid>
		<description><![CDATA[Unlike Zend Framework 1, the view layer in Zend Framework 2 separates the variables assigned to each view model. This means that when you are in the layout view script, you don't automatically have access to variables that were assigned the the action's view model and vice versa. Accessing action variables in the layout Consider [...]]]></description>
			<content:encoded><![CDATA[<p>Unlike Zend Framework 1, the view layer in Zend Framework 2 separates the variables assigned to each view model. This means that when you are in the layout view script, you don't automatically have access to variables that were assigned the the action's view model and vice versa. </p>
<h3>Accessing action variables in the layout</h3>
<p>Consider this controller code:</p>
<pre class="phpcode"><span style="color: #0000BB">
</span><span style="color: #007700">class&nbsp;</span><span style="color: #0000BB">IndexController&nbsp;</span><span style="color: #007700">extends&nbsp;</span><span style="color: #0000BB">ActionController
</span><span style="color: #007700">{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">indexAction</span><span style="color: #007700">()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;array(</span><span style="color: #DD0000">'myvar'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #DD0000">'test'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;}
}
</span>
</span></code></pre>
<p>If you are in the layout.phtml, then to retrieve this value you do:</p>
<p><strong>layout.phtml:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php
$children&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">viewModel</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getCurrent</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getChildren</span><span style="color: #007700">();
</span><span style="color: #0000BB">$child&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$children</span><span style="color: #007700">[</span><span style="color: #0000BB">0</span><span style="color: #007700">];
</span><span style="color: #0000BB">?&gt;
</span>&lt;!--&nbsp;some&nbsp;HTML&nbsp;--&gt;
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">escape</span><span style="color: #007700">(</span><span style="color: #0000BB">$child</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">myvar</span><span style="color: #007700">);</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
<p>If you really want to make sure you collect the correct child view model, then you could iterate over <tt>$children</tt> and look for the child that has the correct <tt>captureTo</tt> name set. For the action's view model, this defaults to <tt>content</tt>:</p>
<p><strong>layout.phtml:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php
$children&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">viewModel</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getCurrent</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getChildren</span><span style="color: #007700">();
foreach(</span><span style="color: #0000BB">$children&nbsp;</span><span style="color: #007700">as&nbsp;</span><span style="color: #0000BB">$child</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(</span><span style="color: #0000BB">$child</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">captureTo</span><span style="color: #007700">()&nbsp;==&nbsp;</span><span style="color: #DD0000">'content'</span><span style="color: #007700">)&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
</span><span style="color: #0000BB">?&gt;
</span>&lt;!--&nbsp;some&nbsp;HTML&nbsp;--&gt;
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">escape</span><span style="color: #007700">(</span><span style="color: #0000BB">$child</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">myvar</span><span style="color: #007700">);</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
<h3>Accessing layout variables in the action view</h3>
<p>If you have assigned a variable to the layout's view model in, say, an event listener within <tt>Module.php</tt>:</p>
<p><strong>Module.php:</strong> </p>
<pre class="phpcode"><span style="color: #0000BB">
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">public&nbsp;function&nbsp;</span><span style="color: #0000BB">onBootstrap</span><span style="color: #007700">(</span><span style="color: #0000BB">$e</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$application&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$e</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'application'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$viewModel&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$application</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getMvcEvent</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getViewModel</span><span style="color: #007700">();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$viewModel</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">some_config_var&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #DD0000">'12345'</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}
</span>
</span></code></pre>
<p>This is how you access <tt>some_config_var</tt> in the action view:</p>
<p><strong>view/index/index.html:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">escape</span><span style="color: #007700">(</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">layout</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">some_config_var</span><span style="color: #007700">);&nbsp;</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
<p>Another, more long winded way is to use the <tt>getRoot()</tt> method on the <tt>viewModel</tt> view helper:</p>
<p><strong>view/index/index.html:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php
$layoutViewModel&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">viewModel</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getRoot</span><span style="color: #007700">();&nbsp;
</span><span style="color: #0000BB">?&gt;
</span>&lt;!--&nbsp;Some&nbsp;HTML&nbsp;--&gt;
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">escape</span><span style="color: #007700">(</span><span style="color: #0000BB">$layoutViewModel</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">some_config_var</span><span style="color: #007700">);&nbsp;</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
<h3>Setting configuration variables into the view</h3>
<p>It therefore follows that if you need to set a variable that could be accessed from any view script, it's easiest to set it into the layout's view model and then access it via the <tt>layout()</tt> view script. This is handy for view layer config variables that you want to store in your config files, such as the Google search API key.</p>
<p><strong>Application/config/module.config.php:</strong> </p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php
</span><span style="color: #007700">return&nbsp;array(
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'layout'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;array(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'google_search_api_key'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #DD0000">'1234567890'</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;),
</span>
</span></code></pre>
<p><strong>Application/Module.php:</strong> </p>
<pre class="phpcode"><span style="color: #0000BB">
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">public&nbsp;function&nbsp;</span><span style="color: #0000BB">onBootstrap</span><span style="color: #007700">(</span><span style="color: #0000BB">$e</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$application&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$e</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'application'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$config&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$e</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'config'</span><span style="color: #007700">);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$viewModel&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$application</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getMvcEvent</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">getViewModel</span><span style="color: #007700">();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$viewModel</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">config&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$config</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">layout</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}
</span>
</span></code></pre>
<p><strong>view/search/index.html:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">layout</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">config</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">google_search_api_key</span><span style="color: #007700">;&nbsp;</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2253&amp;md5=8a905fa9470e87ebdd62aafdcc8abc30" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Faccess-view-variables-in-another-view-model%2F&amp;language=en_GB&amp;category=text&amp;title=Access+view+variables+in+another+view+model&amp;description=Unlike+Zend+Framework+1%2C+the+view+layer+in+Zend+Framework+2+separates+the+variables+assigned+to+each+view+model.+This+means+that+when+you+are+in+the+layout+view+script%2C...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Returning JSON using the Accept header in ZF2</title>
		<link>http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/</link>
		<comments>http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 08:16:28 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework 2]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2197</guid>
		<description><![CDATA[Following yesterday's article on returning JSON from a ZF2 controller action, Lukas suggested that I should also demonstrate how to use the Accept header to get JSON. So this is how you do it! Set up the JsonStrategy We set up the JsonStrategy as we did in returning JSON from a ZF2 controller action. Return [...]]]></description>
			<content:encoded><![CDATA[<p>Following yesterday's article on <a href="/zend-framework-2/returning-json-from-a-zf2-controller-action/">returning JSON from a ZF2 controller action</a>, <a href="http://twitter.com/lsmith">Lukas</a> suggested that I should also demonstrate how to use the Accept header to get JSON. So this is how you do it!</p>
<h3>Set up the JsonStrategy</h3>
<p>We set up the <tt>JsonStrategy</tt> as we did in <a href="/zend-framework-2/returning-json-from-a-zf2-controller-action/">returning JSON from a ZF2 controller action</a>.</p>
<h3>Return a ViewModel from the controller</h3>
<p>As we're letting the <tt>JsonStrategy</tt> intercede for us, we don't need to do anything special in our controller at all. In this case, we simply return a normal <tt>ViewModel</tt> for use by either the <tt>JsonRenderer</tt> or <tt>PhpRenderer</tt> as required:</p>
<p><strong>module/Application/src/Application/Controller/IndexController.php:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php

</span><span style="color: #007700">namespace&nbsp;</span><span style="color: #0000BB">ApplicationController</span><span style="color: #007700">;

use&nbsp;</span><span style="color: #0000BB">ZendMvcControllerActionController</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">ZendViewModelViewModel</span><span style="color: #007700">;

class&nbsp;</span><span style="color: #0000BB">IndexController&nbsp;</span><span style="color: #007700">extends&nbsp;</span><span style="color: #0000BB">ActionController
</span><span style="color: #007700">{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">anotherAction</span><span style="color: #007700">()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$matches</span><span style="color: #007700">[]&nbsp;=&nbsp;array(</span><span style="color: #DD0000">'distance'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">10</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'playground'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;array(</span><span style="color: #DD0000">'a'</span><span style="color: #007700">=&gt;</span><span style="color: #0000BB">1</span><span style="color: #007700">));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$matches</span><span style="color: #007700">[]&nbsp;=&nbsp;array(</span><span style="color: #DD0000">'distance'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">20</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'playground'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;array(</span><span style="color: #DD0000">'a'</span><span style="color: #007700">=&gt;</span><span style="color: #0000BB">2</span><span style="color: #007700">));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$matches</span><span style="color: #007700">[]&nbsp;=&nbsp;array(</span><span style="color: #DD0000">'distance'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">30</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'playground'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;array(</span><span style="color: #DD0000">'a'</span><span style="color: #007700">=&gt;</span><span style="color: #0000BB">3</span><span style="color: #007700">));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$result&nbsp;</span><span style="color: #007700">=&nbsp;new&nbsp;</span><span style="color: #0000BB">ViewModel</span><span style="color: #007700">(array(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'success'</span><span style="color: #007700">=&gt;</span><span style="color: #0000BB">true</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'results'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">$matches</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;));
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;</span><span style="color: #0000BB">$result</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
</span>
</span></code></pre>
<p>with our HTML view script:</p>
<p><strong>module/Application/view/index/another.phtml:</strong></p>
<pre class="phpcode">
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">if&nbsp;(</span><span style="color: #0000BB">$success</span><span style="color: #007700">):&nbsp;</span><span style="color: #0000BB">?&gt;
</span>
&lt;h2&gt;Results&lt;/h2&gt;

&lt;ul&gt;
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">foreach&nbsp;(</span><span style="color: #0000BB">$results&nbsp;</span><span style="color: #007700">as&nbsp;</span><span style="color: #0000BB">$row</span><span style="color: #007700">):&nbsp;</span><span style="color: #0000BB">?&gt;
</span>&nbsp;&nbsp;&nbsp;&nbsp;&lt;li&gt;Distance:&nbsp;<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">echo&nbsp;</span><span style="color: #0000BB">$this</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">escape</span><span style="color: #007700">(</span><span style="color: #0000BB">$row</span><span style="color: #007700">[</span><span style="color: #DD0000">'distance'</span><span style="color: #007700">]);</span><span style="color: #0000BB">?&gt;</span>m&lt;/li&gt;
<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">endforeach;&nbsp;</span><span style="color: #0000BB">?&gt;
</span>&lt;/ul&gt;

<span style="color: #0000BB">&lt;?php&nbsp;</span><span style="color: #007700">endif;&nbsp;</span><span style="color: #0000BB">?&gt;
</span>
</span></code></pre>
<p>So if you set up a route and browse to it, you'll see a nicely rendered page.</p>
<h3>Retrieving the data as JSON</h3>
<p>To retrieve the data via JSON, we need a client where we can set the Accept header. We'll use <tt>curl</tt> for this test. When doing anything with APIs and testing, we head over to <a href="http://twitter.com/lornajane">LornaJane</a>'s blog for the <a href="http://www.lornajane.net/posts/2008/Curl-Cheat-Sheet">Curl Cheat Sheet</a> and use this command line:</p>
<pre>
curl -H "Accept: application/json" http://zf2test.dev/json/another
</pre>
<p>and you should see the output of:</p>
<pre>
{
  "content":{
    "success":true,
    "results": [
      {"distance":10,"playground":{"a":1}},
      {"distance":20,"playground":{"a":2}},
      {"distance":30,"playground":{"a":3}}
    ]
  }
}
</pre>
<p>(Formatted for readability - you get the result back on a single line from <tt>curl</tt>.)</p>
<p>This way you can use the same controllers for your HTML views and for returning JSON to those clients that can use it.</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2197&amp;md5=96ea55c57fca93c49f1f14e1104716a7" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework-2/returning-json-using-the-accept-header-in-zf2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Freturning-json-using-the-accept-header-in-zf2%2F&amp;language=en_GB&amp;category=text&amp;title=Returning+JSON+using+the+Accept+header+in+ZF2&amp;description=Following+yesterday%27s+article+on+returning+JSON+from+a+ZF2+controller+action%2C+Lukas+suggested+that+I+should+also+demonstrate+how+to+use+the+Accept+header+to+get+JSON.+So+this+is...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Returning JSON from a ZF2 controller action</title>
		<link>http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/</link>
		<comments>http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 09:55:48 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Zend Framework 2]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2174</guid>
		<description><![CDATA[The new view layer in Zend Framework 2 can be set up to return JSON rather than rendered HTML relatively easily. There are two steps to this: Set up the JsonStrategy Firstly we need to set up the view's JsonStrategy to check to a situation when returning JSON is required and then to render out [...]]]></description>
			<content:encoded><![CDATA[<p>The new view layer in Zend Framework 2 can be set up to return JSON rather than rendered HTML relatively easily. There are two steps to this:</p>
<h3>Set up the JsonStrategy</h3>
<p>Firstly we need to set up the view's <tt>JsonStrategy</tt> to check to a situation when returning JSON is required and then to render out JSON for us. The <tt>JsonStrategy</tt> will cause the <tt>JsonRenderer</tt> to be run in two situations:</p>
<ol>
<li>The view model returned by the controller action is a <tt>JsonModel</tt></li>
<li>The HTTP Accept header sent in the Request include "application/json"</li>
</ol>
<p>The enable the <tt>JsonStrategy</tt>, we simply attach it to the view's event manager with a reasonably high priority. This can be done in our Application's <tt>Module</tt> class. Firstly we create an <tt>onBootstrap()</tt> callback on the <tt>bootstrap</tt> event and then we implement <tt>onBootstrap()</tt> to attaché the <tt>JsonStrategy</tt>:</p>
<p><strong>module/Application/Module.php:</strong></p>
<pre class="phpcode"><span style="color: #0000BB">
</span><span style="color: #007700">class&nbsp;</span><span style="color: #0000BB">Module&nbsp;</span><span style="color: #007700">implements&nbsp;</span><span style="color: #0000BB">AutoloaderProvider
</span><span style="color: #007700">{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">init</span><span style="color: #007700">(</span><span style="color: #0000BB">Manager&nbsp;$moduleManager</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$events&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">StaticEventManager</span><span style="color: #007700">::</span><span style="color: #0000BB">getInstance</span><span style="color: #007700">();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$events</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">attach</span><span style="color: #007700">(</span><span style="color: #DD0000">'bootstrap'</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'bootstrap'</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;array(</span><span style="color: #0000BB">$this</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">'onBootstrap'</span><span style="color: #007700">));
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">onBootstrap</span><span style="color: #007700">(</span><span style="color: #0000BB">Event&nbsp;$e</span><span style="color: #007700">)
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$application&nbsp;&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$e</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getParam</span><span style="color: #007700">(</span><span style="color: #DD0000">'application'</span><span style="color: #007700">);&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">/*&nbsp;@var&nbsp;$application&nbsp;\Zend\Mvc\Application&nbsp;*/
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$locator&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$application</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getLocator</span><span style="color: #007700">();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$view&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$locator</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">get</span><span style="color: #007700">(</span><span style="color: #DD0000">'Zend\View\View'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$jsonStrategy&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #0000BB">$locator</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">get</span><span style="color: #007700">(</span><span style="color: #DD0000">'Zend\View\Strategy\JsonStrategy'</span><span style="color: #007700">);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$view</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">events</span><span style="color: #007700">()-&gt;</span><span style="color: #0000BB">attach</span><span style="color: #007700">(</span><span style="color: #0000BB">$jsonStrategy</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">100</span><span style="color: #007700">);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #FF8000">//&nbsp;more&nbsp;methods&nbsp;such&nbsp;as&nbsp;getConfig()&nbsp;and&nbsp;getAutoloaderConfig()
</span><span style="color: #007700">}
</span>
</span></code></pre>
<p>As you can see, in <tt>init()</tt> we grab the <tt>StaticEventManager</tt> to attach our <tt>onBootstrap()</tt> method to the <tt>bootstrap</tt> event. Then, within <tt>onBootstrap()</tt>, we grab the view and the <tt>JsonStrategy</tt> from the locator (via application) and attach the <tt>JsonStrategy</tt> to the view's <tt>events()</tt> event manager.</p>
<h3>Return a JsonModel from the controller action</h3>
<p>To send JSON to the client when the Accept header isn't application/json, we use a <tt>JsonModel</tt> in a controller action like this:</p>
<p><strong>module/Application/src/Application/Controller/IndexController.php:</strong></p>
<pre class="phpcode"><span style="color: #0000BB">
</span><span style="color: #007700">namespace&nbsp;</span><span style="color: #0000BB">Application</span><span style="color: #007700">\</span><span style="color: #0000BB">Controller</span><span style="color: #007700">;

use&nbsp;</span><span style="color: #0000BB">Zend</span><span style="color: #007700">\</span><span style="color: #0000BB">Mvc</span><span style="color: #007700">\</span><span style="color: #0000BB">Controller</span><span style="color: #007700">\</span><span style="color: #0000BB">ActionController</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">Zend</span><span style="color: #007700">\</span><span style="color: #0000BB">View</span><span style="color: #007700">\</span><span style="color: #0000BB">Model</span><span style="color: #007700">\</span><span style="color: #0000BB">ViewModel</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">Zend</span><span style="color: #007700">\</span><span style="color: #0000BB">View</span><span style="color: #007700">\</span><span style="color: #0000BB">Model</span><span style="color: #007700">\</span><span style="color: #0000BB">JsonModel</span><span style="color: #007700">;

class&nbsp;</span><span style="color: #0000BB">IndexController&nbsp;</span><span style="color: #007700">extends&nbsp;</span><span style="color: #0000BB">ActionController
</span><span style="color: #007700">{
&nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;function&nbsp;</span><span style="color: #0000BB">indexAction</span><span style="color: #007700">()
&nbsp;&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000BB">$result&nbsp;</span><span style="color: #007700">=&nbsp;new&nbsp;</span><span style="color: #0000BB">JsonModel</span><span style="color: #007700">(array(
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'some_parameter'&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #DD0000">'some&nbsp;value'</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #DD0000">'success'</span><span style="color: #007700">=&gt;</span><span style="color: #0000BB">true</span><span style="color: #007700">,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;</span><span style="color: #0000BB">$result</span><span style="color: #007700">;
&nbsp;&nbsp;&nbsp;&nbsp;}
}
</span>
</span></code></pre>
<p>The output will now be JSON. Obviously, if you're sending JSON back based on the Accept header, then you can return a normal ViewModel.</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2174&amp;md5=d823f68ea36186881822028c47cfcf22" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/zend-framework-2/returning-json-from-a-zf2-controller-action/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fzend-framework-2%2Freturning-json-from-a-zf2-controller-action%2F&amp;language=en_GB&amp;category=text&amp;title=Returning+JSON+from+a+ZF2+controller+action&amp;description=The+new+view+layer+in+Zend+Framework+2+can+be+set+up+to+return+JSON+rather+than+rendered+HTML+relatively+easily.+There+are+two+steps+to+this%3A+Set+up+the...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Automatic Apache vhosts</title>
		<link>http://akrabat.com/computing/automatic-apache-vhosts/</link>
		<comments>http://akrabat.com/computing/automatic-apache-vhosts/#comments</comments>
		<pubDate>Mon, 26 Mar 2012 07:24:50 +0000</pubDate>
		<dc:creator>Rob...</dc:creator>
				<category><![CDATA[Computing]]></category>

		<guid isPermaLink="false">http://akrabat.com/?p=2158</guid>
		<description><![CDATA[One thing that I've wanted to implement for a while now is automatic vhosts on my dev box. The idea is that I want to drop a folder into a directory and have it automatically turned into a vhost for me accessible at http://foldername.dev. It turns out that this isn't nearly as hard as expected [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that I've wanted to implement for a while now is automatic vhosts on my dev box. The idea is that I want to drop a folder into a directory and have it automatically turned into a vhost for me accessible at <tt>http://<em>foldername</em>.dev</tt>. It turns out that this isn't nearly as hard as expected which is usually the case with things that I've been putting off!</p>
<p>This is how to do it.</p>
<h4>Apache configuration</h4>
<p>The Apache magic is in an extension called <tt><a href="http://httpd.apache.org/docs/2.2/mod/mod_vhost_alias.html">mod_vhost_alias</a></tt> which you may need to enable in your <tt>httpd.conf</tt> file. </p>
<p>You can then set up the <tt>VirtualHost</tt> wherever you keep such things. On a stock OS X, the <tt>extras/httpd-vhosts.conf</tt> file is used. </p>
<p>Add the following to the bottom:</p>
<pre>
&lt;Virtualhost *:80>
    VirtualDocumentRoot &quot;/www/dev/%1/public&quot;
    ServerName vhosts.dev
    ServerAlias *.dev
    UseCanonicalName Off
    LogFormat &quot;%V %h %l %u %t \&quot;%r\&quot; %s %b&quot; vcommon
    ErrorLog &quot;/www/dev/vhosts-error_log&quot;
    &lt;Directory &quot;/www/dev/*&quot;>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    &lt;/Directory>
&lt;/Virtualhost>
</pre>
<p>In the <tt>VirtualHost</tt> configuration, I have used the <tt>ServerAlias</tt> and <tt>VirtualDocumentRoot</tt> directives to map <tt>http://<em>foldername</em>.dev</tt> to the directory <tt>/www/dev/<em>foldername</em>/public</tt>. Hence, any folder that I place in <tt>/www/dev</tt> will have its own virtual host. Alter these appropriately for your set-up.</p>
<p>Don't forget to restart Apache.</p>
<p>Unfortunately, the computer hasn't a clue how to handle http://foldername.dev and the obvious solution is to run a local DNS server. Another solution is to use a PAC file.</p>
<h4>DNS server configuration</h4>
<p>This is easy enough with <a href="http://www.thekelleys.org.uk/dnsmasq/doc.html">dnsmasq</a>. On OS X, use <a href="http://mxcl.github.com/homebrew/">Homebrew</a> to install like this: <tt>brew install dnsmasq</tt>. On Linux, use your package manager; on Windows, you're own your own!</p>
<p>Note that on OS X, you should set it to start up automatically using launchd as noted in the instructions after installation. You also need to copy the configuration file to <tt>/etc</tt> using: <tt>cp /usr/local/Cellar/dnsmasq/2.57/dnsmasq.conf.example /usr/local/etc/dnsmasq.conf</tt> (or whatever the latest version number is). on Linux, I would guess that your package manager provides a dnsmasq.conf file in <tt>/etc</tt> or <tt>/etc/dnsmasq</tt>.</p>
<p>Next, edit <tt>dnsmasq.conf</tt> file and added the following lines to the bottom:</p>
<pre>
listen-address=127.0.0.1
address=/.dev/127.0.0.1
</pre>
<h4>Add the name server to your network configuration</h4>
<p>On OS X, Go to <em>System Preferences</em> -> <em>Network</em> -> <em>{Wifi or Ethernet}</em> -> <em>Advanced…</em> -> <em>DNS</em> and click on + button at the bottom of the left hand panel and add <strong>127.0.0.1</strong> to the list of DNS servers. Drag 127.0.0.1 at the top of the list.</p>
<p>On Linux, you should use the appropriate GUI tools for your distribution or potentially edit <tt>etc/dhcp/dhclient.conf</tt> and uncomment the <tt>domain-name-servers 127.0.0.1;</tt> on line 20 (on Ubuntu).</p>
<p>Restart dnsmasq and you should now be able to execute <tt>host test.dev</tt> on the command line and see <tt>127.0.0.1</tt> as the resultant address.</p>
<h4>Alternative to DNS server: PAC file</h4>
<p>Since publishing this article, <a href="http://twitter.com/inxilpro">Chris Morell</a> pointed out that you can also use PAC files rather than install a DNS server. Details are on his <a href="http://cmorrell.com/webdev/automatic-virtual-hosts-w-proxy-auto-config-768">blog post</a>.</p>
<h4>Check it works</h4>
<p>Create a directory called <tt>test</tt> in your <tt>dev</tt> directory. Within <tt>test</tt>, create <tt>public/index.php</tt> and within <tt>index.php</tt> add some code to prove it works. e.g. <tt>< ;?php echo "Hello World"; ?>;</tt></p>
<p>If you navigate to http://test.dev, you should see "Hello World" displayed.</p>
<h4>Caveats</h4>
<p>A couple of caveats:</p>
<ul>
<li><tt>DOCUMENT_ROOT</tt> is not /www/dev/test as you'd expect. Instead it is the global document root. See <a href="https://gist.github.com/2208990">this gist</a> for a neat way to solve this using a prepend file.</li>
<li>If you use mod_rewrite, then you'll need a <tt>RewriteBase /</tt> in your <tt>.htaccess</tt> file. Alternatively, you can change the <tt>Directory</tt> section of your vhost to do the rewriting for you if all your projects are alike. Something like this should work:
<pre>
    &lt;Directory &quot;/www/dev/*&quot;>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        Allow from all

        RewriteEngine On
        RewriteBase /
        RewriteCond %{REQUEST_FILENAME} -s [OR]
        RewriteCond %{REQUEST_FILENAME} -l [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^.*$ - [NC,L]
        RewriteRule ^.*$ index.php [NC,L]
    &lt;/Directory>
</pre>
</li>
</ul>
<h4>All done</h4>
<p>That's it. You can now create as many projects as you like without having to worry about setting up new virtual hosts or modifying you hosts file!</p>
 <p><a href="http://akrabat.com/?flattrss_redirect&amp;id=2158&amp;md5=07bcda0d15dbd1eac3d0f82a381ad628" title="Flattr" target="_blank"><img src="http://akrabat.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://akrabat.com/computing/automatic-apache-vhosts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="https://flattr.com/submit/auto?user_id=akrabat&amp;popout=1&amp;url=http%3A%2F%2Fakrabat.com%2Fcomputing%2Fautomatic-apache-vhosts%2F&amp;language=en_GB&amp;category=text&amp;title=Automatic+Apache+vhosts&amp;description=One+thing+that+I%27ve+wanted+to+implement+for+a+while+now+is+automatic+vhosts+on+my+dev+box.+The+idea+is+that+I+want+to+drop+a+folder+into+a...&amp;tags=blog" type="text/html" />
	</item>
	</channel>
</rss>

