<?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>melp.nl</title>
	<atom:link href="http://melp.nl/feed/" rel="self" type="application/rss+xml" />
	<link>http://melp.nl</link>
	<description>A geek&#039;s outlet on open source, web development and related stuff</description>
	<lastBuildDate>Sun, 16 Jun 2013 18:51:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>PHP: We are getting slow and sluggish, and we&#8217;re lazy and arrogant about it.</title>
		<link>http://melp.nl/2013/06/php-we-are-getting-slow-and-sluggish-and-were-lazy-and-arrogant-about-it/</link>
		<comments>http://melp.nl/2013/06/php-we-are-getting-slow-and-sluggish-and-were-lazy-and-arrogant-about-it/#comments</comments>
		<pubDate>Sun, 16 Jun 2013 18:31:33 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=754</guid>
		<description><![CDATA[In my most recent blog, I wrote about how I feel that too much of the world&#8217;s logic is coming onto the shoulders of PHP, these days. Today, I&#8217;m will be showing you why and how PHP&#8217;s powers could be harnessed better and more. We, as PHP web developers, should be absolutely fully aware that [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="/?p=744">most recent blog</a>, I wrote about how I feel that too much of the world&#8217;s logic is coming onto the shoulders of PHP, these days. Today, I&#8217;m will be showing you why and how PHP&#8217;s powers could be harnessed better and more. We, as PHP web developers, should be absolutely fully aware that we&#8217;re allowing insane amounts of processing power to do too much work when it&#8217;s absolutely unnecessary to do so dynamically.</p>

<h1>Say what now?</h1>

<p>Here&#8217;s part of the problem: PHP developers usually don&#8217;t really know the difference between what&#8217;s static and what&#8217;s not. Simply put: there is only one variable. The request. Anything else should be as static as possible. If I would introduce a configuration file with loads of variables, a typical C programmer would argue: &#8220;Those are build parameters. They don&#8217;t change unless your environment changes, so they are static and should be handled by a preprocessor and macros. You don&#8217;t need continuous evaluation of static data&#8221;. A typical Java programmer would probably put stuff like that in a static final constant property somewhere, knowing (or assuming) that the compiler will optimize and inline usage of these settings <sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>.</p>

<p>PHP doesn&#8217;t do either. We have no preprocessor, and we have no compiler optimizations on that level. Mainly, because PHP originally was a platform that was supposed to do some simple processing and spew out some dynamic content, as fast as possible. But the PHP community is growing up. We want real OO programming, we use design patterns, we think about dependencies, maintainability, scalability. Stuff that grown-ups do.</p>

<h1>But then, what the <em>hell</em> is wrong with this picture?!</h1>

<p>I was having performance trouble with one of my Symfony projects at work. So I decided to do some performance testing. Please note that I absolutely love Symfony. There is no framework out there that will actually help you design your application better, and it brought me and many of my colleagues more joy in life. Really. Please understand that this isn&#8217;t really about Symfony, because I am pretty sure most of it goes for any other current-generation framework.</p>

<p>I set up some benchmarking comparisons. This isn&#8217;t scientific evidence, to be frank. This is experimental science. I was having a hunch, and this indicates that my hunch was correct. So here goes.</p>

<h2>The example controller in the Symfony standard edition</h2>

<p>Whenever you start a Symfony project, you would typically bootstrap from the standard edition, remove the demo code and add your own bundle. The example controller does something pretty simple. It responds to a URL <code>/hello/...</code>, where the dots may contain anything but a forward slash. Here&#8217;s the code:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DefaultController <span style="color: #000000; font-weight: bold;">extends</span> Controller
<span style="color: #009900;">&#123;</span>
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/hello/{name}&quot;)
     * @Template()
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> indexAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'name'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre>

<p>The idea is simple. /hello/{name} routes to this controller, the controller returns an array of named variables, and the <code>@Template</code> annotation makes sure the template corresponding to the controller is rendered. This is usually a twig template, and in this case, the template looks like this:</p>

<pre><code>Hello {{ name }}!
</code></pre>

<h2>Not just to be a pain in the ass&#8230;</h2>

<p>How would you have done this 15 years ago? Probably something like this. Create a PHP file in <code>hello/index.php</code> containing:</p>

<pre class="php" style="font-family:monospace;">Hello <span style="color: #000000; font-weight: bold;">&lt;?=</span> <a href="http://www.php.net/htmlspecialchars"><span style="color: #990000;">htmlspecialchars</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'name'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>!</pre>

<p>and a <code>.htaccess</code> in the web root containing:</p>

<pre><code>RewriteEngine On

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule hello/([^/]+) hello/index.php?name=$1 [L]
</code></pre>

<p>Right? It doesn&#8217;t really do anything more than that. And if I&#8217;m absolutely honest about it, useless as the example may be, it shouldn&#8217;t be done any other way.</p>

<p>So, just for the sake of curiosity, lets see what a difference in performance this is. I set up two identically configured hosts on my local machine in Apache, but with different webroots, just to be as close as possible to a regular development environment I normally use. The first web root is the regular <code>web/</code> directory from Symfony (and I renamed it to web-1). The second is another directory containing the setup as described above.</p>

<p>With &#8216;ab&#8217; (<a href="http://httpd.apache.org/docs/2.2/programs/ab.html">Apache Benchmark</a>), you can get a pretty good idea of performance increases if you&#8217;re optimizing your website, one way or another. You can basically pass in an URL and have multiple concurrent users hammer that URL for a specified number of times. So that&#8217;s what I did. I usually start with 1000 requests, with 20 concurrent users. This usually gives a good comparable impression of speed.</p>

<p>First off, the <code>dev</code>, debugging version of the symfony app. Of course, you wouldn&#8217;t normally test performance in a development or debugging environment, but it&#8217;s here for the sake of comparison. Here&#8217;s the most relevant<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup> results of &#8216;ab&#8217;.</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      20                    
Time taken for tests:   25.058 seconds        
Complete requests:      1000                  
Requests per second:    39.91 [#/sec] (mean)</pre>

<p>Second, the <code>prod</code>, non-debugging version of the symfony app.</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      20
Time taken for tests:   5.302 seconds
Complete requests:      1000
Requests per second:    188.61 [#/sec] (mean)</pre>

<p>That seems pretty decent. Just under 200 requests per second were managed. Let&#8217;s increase concurrency to see what happens:</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      250
Time taken for tests:   7.153 seconds
Complete requests:      1000
Requests per second:    139.80 [#/sec] (mean)</pre>

<p>A slight drop in performance was to be expected, but it is at least pretty steady and stable.</p>

<p>Now let see how the 1998 version of the same &#8220;<em>application</em>&#8221; would perform.</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      20
Time taken for tests:   0.178 seconds
Complete requests:      1000
Requests per second:    5614.76 [#/sec] (mean)</pre>

<p>Wait. What? Over 5500 requests handled <em>each second</em>? That means a performance increase of <strong>30</strong>. Not 30%, a <strong>FACTOR</strong> of 30. Nearly 30 times faster. The last time I saw numbers like these were when I ran benchmarks on a Varnish cache&#8230;.</p>

<p>This would mean that if I were to run the same test with 30 times as much requests, the 1998 version should manage equally:</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      20
Time taken for tests:   4.482 seconds
Complete requests:      30000
Requests per second:    6693.93 [#/sec] (mean)</pre>

<p>At these numbers, the measurements apparently show even better results! And if we would increase concurrency, it would at least have the same relative performance as the other one:</p>

<pre class="shell" style="font-family:monospace;">Concurrency Level:      250
Time taken for tests:   6.366 seconds
Complete requests:      30000
Requests per second:    4712.83 [#/sec] (mean)</pre>

<p>Let&#8217;s look at this for a few seconds. Just to be sure we understand what this means. This means the stripped version of the functionality runs roughly a factor 30 faster than the one implemented using the framework, both with 20 and 250 concurrent users.</p>

<p>But if these numbers are possible, why then, why do we think all the framework&#8217;s benefits outweigh these mind-boggling disadvantages?</p>

<h1>The counter-arguments</h1>

<h2>You have no request listeners and therefore no security, no logging, etc, etc&#8230;</h2>

<p>I know. And you are right. I don&#8217;t. But none of those are needed in this example. And that&#8217;s exactly what&#8217;s wrong with our mindset. We load tons of utilities and tons of logic to requests of which in 80% of the cases, only 20% actually need, and we keep on saying that the ease of use and the well-thought design are good arguments to have such a horrendous performance impact.</p>

<p>Be honest. If you would buy a new server, would you rather have it installed bare bone without any software on it so you can carefully pick your stuff, or would you have the entire Ubuntu Software center installed, so you can use it whenever you can?</p>

<p>Sure, there is a middle road, but lets find a middle road that is the best, not the one that is the most convenient just for us developers.</p>

<h2>But you can cache it!</h2>

<p>There is only one right answer to such a suggestion. Caching sucks<sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup>. Yes, I know, caching is cool, because it can make stuff insanely fast (try Varnish one time. Unsavory goo will drip from your lips, I promise you). But that&#8217;s not the point, really. Caching complicates stuff. Complications are just like expensive toys. 1) You don&#8217;t really need them, 2) they make you worry about breaking things that shouldn&#8217;t really matter and 3) you already have enough of them.</p>

<h2>So we should install php3 again and get rid of the frameworks?</h2>

<p>Balls, no! This is something the people behind the frameworks should be aware of. But at the very least, the people using them should be aware of it. Don&#8217;t tell your project manager (or worse, your client) that the performance is okay, and that you just need a few days R&amp;D to implement caching, just tell them the framework is relatively slow but that you think the extra cost in hardware and complexity of caching mechanisms outweigh the design and maintainability benefits. And be very careful to really mean it and know what you&#8217;re talking about.</p>

<h1>Code generation is paramount to performance!</h1>

<p>I&#8217;m not the type of guy to point out problems and not think of solutions beforehand. I have been thinking about this for quite some time, and thought of building something myself. But the fact of the matter is: I don&#8217;t have the time nor the persuasive character to actually get it done.</p>

<p>What would be needed is a build system that &#8220;folds out&#8221; into smaller pieces of somewhat repetitive PHP. We write the development code just like we did before, but when deploying to a non-development environment, all the bits and pieces should be as static as possible. Anything that is dynamic but could, in theory, be static, must be factored out. This means, in case of Symfony, that</p>

<ul>
<li>It is a bad practice (or even unsupported) to have dynamics inside your Bundle classes. Use the service container for this. This way, the bundles needn&#8217;t be loaded nor initialized on each request;</li>
<li>The service container and accompanying files should be loaded lazily. This can be achieved using require_once calls whenever necessary. The compiled code should do the same.</li>
<li>Service container and compiled DI code (we have this already, but could even be more effective) compiles into separate files in stead of a big class that gets loaded everytime.</li>
<li>Configuration must be compiled statically</li>
<li>Templating must be optimized such that it generates the most efficient PHP code possible. Using magic like the detection of &#8216;getters&#8217; and such should be removed. May be even consider it a bad practice to use objects in templates at all.</li>
<li>Routing must be done statically. Dynamic routing is runtime logic and can be done inside the controllers.</li>
<li>Request listener code is compiled into the controller files, so templating listeners, error handling and security are as efficient as possible.</li>
<li>Resolution of bundle aliases is done at compile time</li>
<li>Handling sub requests is done by simple includes</li>
</ul>

<p>And on goes the list.</p>

<h1>And now, for some action</h1>

<p>I have built a little &#8220;<a href="https://github.com/drm/symfony-performance">proof of concept</a>&#8221; that shows you the idea. I wrote the resulting code by hand, but with most of the logic already in place, a compiler with some optimization passes in the resulting AST could do anything that i did by hand automatically.</p>

<p>Here&#8217;s the performance impact difference:</p>

<h4>The &#8216;<code>hello {name}</code>&#8216; example:</h4>

<table>
<thead>
<tr>
  <th>Standard Symfony</th>
  <th>Optimized version</th>
</tr>
</thead>
<tbody>
<tr>
  <td>188 rps</td>
  <td>1640 rps</td>
</tr>
</tbody>
</table>

<h4>An example using doctrine</h4>

<table>
<thead>
<tr>
  <th>Standard Symfony</th>
  <th><a href="https://github.com/drm/symfony-performance/blob/master/web-3/melptesting/default/db.php">Optimized, with entire service container</a></th>
  <th><a href="https://github.com/drm/symfony-performance/blob/master/web-3/melptesting/default/db-optim.php">Optimized, only doctrine service</a></th>
</tr>
</thead>
<tbody>
<tr>
  <td>~135 rps</td>
  <td>~320 rps</td>
  <td>~350 rps</td>
</tr>
</tbody>
</table>

<p>In the second example, (which is configured at route <code>db/{name}</code>), the entire service container is loaded, by including the appProdProjectContainer from the cache. In the last example, routed through <code>db-optim/{name}</code>, the doctrine service and it&#8217;s dependencies are loaded by including <a href="https://github.com/drm/symfony-performance/tree/master/app/services">files with their service definition</a>. This adds another ~10% increase in performance, which is still worth considering, imho.</p>

<p>Note that the doctrine services only use per-request caching (ArrayCache), in this example.</p>

<h1>What&#8217;s the catch?</h1>

<p>The catch is, most of the overhead from Symfony&#8217;s kernel is from the request listeners. There are a whopping 15 (fifteen) services that listen to every request in Symfony. All of these listeners can be optimized into pieces of code which are included in the controller files, where the &#8220;listening logic&#8221; (i.e., checking if the listener should do anything) can be done by a static line of code. In the examples above, you can see this happening for the templating listener, which is only checking if the return value of the controller is an array. The fact that it&#8217;s in place right there, can be controlled by the <code>@Template</code> annotation. The same would fly for <code>@Secure</code> and <code>@Route</code> annotations. Some listeners contain global static logic (such as the locale listener) or are generic, but nonetheless static (such as exception listeners.</p>

<p>With the Kernel structure as it is now, there is no way to have these listeners come into play only when needed. They are initialized every request, and therefore <strong>all dependencies</strong> that these listeners may have, are initialized. There is only one way to get around this. Compile all initialization into the controller files, but guarded within the conditions these listeners should provide. Just like the <a href="https://github.com/drm/symfony-performance/blob/master/web-3/melptesting/default/index.php#L11"><code>is_array()</code> example</a> for the logic of the Templating listener, this can be done for any other listener.</p>

<p>The sharp reader must have noticed that I disabled all listener logic in my example. This is the reason.</p>

<h1>To conclude</h1>

<p>I have posted before about a <a href="/?p=662">paradigm shift towards declarative programming</a>. I am also arguing that this shift should include a better sense of balance between performance and maintainability. PHP&#8217;s road to success was paved by performance. If we lose that, there is not much reason left not to choose other platforms.</p>

<p>A final disclaimer: I am not bashing. I hope that this will lead to more good in the PHP community. At the very least, I dropped my thoughts and can leave it simmering for now. If you read the post entirely, thanks for your patience.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>I&#8217;m not sure if the Java compiler works this way, but I&#8217;m just assuming that it does some kind of optimization for constant values.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:2">
<p>I am using the following command line to do these tests: <code>ab -n 1000 -c 20 http://the/url/ | egrep '^(Time taken|Concur|Requests per|Complete)'</code>. The regular output of ab holds a lot more statistical information. I am performing these tests locally, so they vary a lot; I have of course some other programs running which interfere with the performance. I am aware of that. The numbers don&#8217;t really matter that much, but the relative differences do.&#160;<a href="#fnref:2" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:3">
<p>Cache invalidation is one of the <a href="http://martinfowler.com/bliki/TwoHardThings.html">two hard things</a> in computer science. The other one is naming things and off-by-one errors.&#160;<a href="#fnref:3" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2013/06/php-we-are-getting-slow-and-sluggish-and-were-lazy-and-arrogant-about-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP in the web development world: are we doing it all wrong?</title>
		<link>http://melp.nl/2013/01/php-in-the-web-development-world-are-we-doing-it-all-wrong/</link>
		<comments>http://melp.nl/2013/01/php-in-the-web-development-world-are-we-doing-it-all-wrong/#comments</comments>
		<pubDate>Sun, 27 Jan 2013 17:19:40 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[theory]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=744</guid>
		<description><![CDATA[Some thoughts and ponderings on how &#8220;the frameworks out there&#8221; might not do it just as right as they should. The UNIX principle applied? Something that is currently overlooked in a large part of the PHP community is that not all design patterns are necessarily implemented in PHP code. Your webserver can be considered the [...]]]></description>
			<content:encoded><![CDATA[<p><em>Some thoughts and ponderings on how &#8220;the frameworks out there&#8221; might not do it just as right as they should.</em></p>

<h1>The UNIX principle applied?</h1>

<p>Something that is currently overlooked in a large part of the PHP community is that not all design patterns are necessarily implemented in PHP code. Your webserver can be considered the front controller of your application too. Routes can be defined using your filesystem and webserver configuration. Not everything has to be Object Oriented to be well organised and well structured. To gain perspective, here are some ideas to think outside the box, and not have OO patterns drive you beyond reason.</p>

<p>Some perfectly good solutions to, for example, caching and distributed processing, are commonly overlooked because of the simple presumption that everything should be done inside PHP or should at least be controlled by PHP. In my opinion, this might be a symptom of the <a href="http://en.wikipedia.org/wiki/Not_Invented_Here">Not Invented Here</a> syndrome, and is thus by definition something to be questioned. It makes modular reimplementation in a different platform or language virtually impossible, which troubles long term development of web applications. You can not and must not feel confident that anything you want can or should be done in PHP. The language is irrelevant, the platform is irrelevant, the choice for PHP should be one based on those aspects that make PHP a better choice than another platform or language. If the outcome <em>is</em> PHP, use it. If it is not, it should be of least possible impact on the design choices you make for the rest of your application.</p>

<h1>Why is the question important?</h1>

<p>We need to be more and more prepared for distributed and parallel processing, which means we need to slice applications down to small and simple bits to be processed on any CPU or filesystem. That means that, while employing nice OO implementations of design patterns inside frameworks like Zend Framework, Symfony and the likes<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>, we are in fact building monolithical applications, that can be called and routed only through a single front controller file (usually index.php), which doesn&#8217;t make the design of the application internals monolithic per se, but does make the application <em>an sich</em> monolithic.</p>

<p>Continuing with this type of development is in huge conflict with various philosophies, such as the <a href="http://www.faqs.org/docs/artu/ch01s06.html">UNIX principle</a>. We build one application that does a lot of things very well<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup>. This UNIX principle is not something to be overlooked lightly, because it is historically the single greatest success factor of free software and UNIX based development such as Linux, BSD, GNU, etc&#8230;, not to mention PHP. Note that free software means &#8220;Free to choose what software you want to use&#8221; also; not only free in terms of money or legalities, but also free in terms of dependency and freedom of choice.</p>

<p>Moreover, note that the UNIX philosophy holds strong resemblance to the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Principle of Least Knowledge</a> and <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">Separation of Concern</a>, which, in my opinion, are by far the two most vital and important fundementals of software design, when keeping maintainability, testability and long term development in mind. Parts of the application that need updating because either the code is irrelevant or some better component has arisen, should be easily cut out and replaced by another. Think of, for example, replacing Apache with NginX, or even replacing the current PHP payment module with a Java one.</p>

<p>Any component in an application should be responsible for one thing in the application, and one thing only. Vice versa, the component that does the job, should be the component that is the very best at that job. You wouldn&#8217;t write your own SQL implementation, if you know there&#8217;s perfectly good relational databases out there. So why build your own page caching mechanism if the webserver can cache pages for you? Why build your own routing and dispatching system if the webserver has perfectly good routing and dispatching systems in place?</p>

<h1>What with those <em>quote</em> MVC <em>unquote</em> frameworks?</h1>

<p>PHP does one thing very well: it is a very fast interpreter of a reasonably simple programming language, and is best suited for processing variables (typically CGI requests) and responding with text output (typically HTML formatted content), while communicating with any backend such as MySQL and filesystems.</p>

<p>MVC frameworks are deviating from this premiss. They hold the PHP application responsible for far more than just handling an incoming request and serving the response. This could be a problem. It complicates the application design very much that all those responsibilities come onto the shoulders of a single application. The danger lies in the fact that inside this application, there might be more trouble identifying the responsibilities and concerns of the different components. If you would separate those responsibilities from the main application, you would find that there is a lot that we&#8217;re dealing with inside our application, which is very irrelevant to the application&#8217;s own concern.</p>

<p>The best example of this is caching. Either caching stuff that is coming from the database (which a properly configured MySQL already does for you), or caching entire pages (which can be done by the web server): this does not necessarily belong in your PHP code. It belongs in your application, yes, but your application consists of more than just PHP. It is the entire stack of software that all follow the UNIX principle: Linux, Apache, PHP and MySQL. Of course, substitute any of the software with an equivalent alternative, if you have reason.</p>

<p>Another example is routing and dispatching. One of the most tedious and tiresome jobs inside your application is making sure that every link is SEO friendly; i.e. that it contains words that are relevant to the page&#8217;s content, and that it&#8217;s hierarchical position is relevant to where the page belongs in the site, while still having an idea of what the canonical url of that page should be to avoid duplicated indexing by search engines. I have had not a single project where this would cost not a few hours &#8211; at best &#8211; to take into account. Why? Because we think to hard about it, and we fear the simple solution might impact performance.</p>

<h1>Where complexity is, is where the problem lies</h1>

<p>Whenever you find you&#8217;re adding complexity to your application because of non-functional requirements such as performance reasons or cost reduction, you need to take a step back and re-evaluate the problem at hand.</p>

<p>A very simple example of this is a YAML file read by a set of PHP classes, rendering a PHP array. This array can be cached in a compiled form using <tt>var_export</tt>. Having the application itself responsible for this compilation will add complexity to the set of responsibilities of the application. It would be much easier to have the application depend on a PHP configuration file, and let some build process make sure the YML file is compiled into PHP.</p>

<p>Another example is compilation of template files. If you have a set of template files in another language than PHP, for example Twig or Smarty, you can have the compilation of these files be part of a build process. This doesn&#8217;t have to be on-the-fly. PHP programmers are used to having stuff work &#8220;on the fly&#8221;, but it is a convenience that can bite you in the ass. It&#8217;s far easier to have a build script that makes sure all cachable data is flushed, than have your application responsible for checking of freshness of these caches. To be even more exact: your application doesn&#8217;t even need to know that the stuff it&#8217;s reading is actually a cache. It only needs some files, and they&#8217;re there.</p>

<p>My final example is SEO friendly URL&#8217;s. There is no reason the application itself should worry about this. We have lots of available tools to rewrite outbound and inbound url&#8217;s to whatever we need to rewrite. The only thing this tool needs to know is a very simple &#8220;from&#8221; => &#8220;to&#8221; mapping of all these URL&#8217;s, and that&#8217;s it. The program can translate friendly URL&#8217;s into internal URL&#8217;s, and vice versa. If the program does that, and does that very well, we are out of the pickle.</p>

<h1>Data versus layout</h1>

<p>Formatting the data of your application in to whatever format (usually HTML), is the responsibility of some sort of view renderer. Action Controllers have the responsibility in translating a request into some sort of response, and usually dispatch to a view renderer internally to have the response formatted as HTML. Now here&#8217;s something fishy going on. The action controllers gain three responsibilities in this way; two explicit (handling the request with the appropriate action and returning it&#8217;s result) and one implicit: rendering the result. Since the result of any action always is data, the action controller should not be responsible for the formatting of the data. It is in fact irrelevant at that point in time. You&#8217;ll just want to know what the result of that action is; either some state (success or failure) or some data. It makes much more sense to have an intermediate format for this (be it a PHP array of data, XML, JSON, or some other form), and have the view on this data or result be detached entirely from the action&#8217;s operation. This way, the action controller has only one responsibility: returning the request&#8217;s result. Note that the request can be defined as simply as a few method parameters; it needn&#8217;t be an HTTP request as such.</p>

<p>The front controller of the application can be responsible for dispatching one front request to one or more action requests, that all have their result. Whether or not the front controller renders this response as HTML is moot.</p>

<h1>Why not utilize PHP as a build result?</h1>

<p>I think we all might gain more in using PHP as a result of our project&#8217;s build. We might simply program in a higher level programming language, and have some compilation or build process build all kinds of php files, that may contain a meriad of repetitive code, just because that is what ultimately the PHP interpreter is best at. Simply <em>preprocessing</em> the <em>hypertext</em>, in stead of doing it the other way around and having PHP implement byte code caches and high level programming features. Maybe PHP was the right language right before it got cocky&#8230;</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>Which I am, of course, a great supporter of. Design inside the code is never something to be taken lightly.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:2">
<p>Let&#8217;s at least assume that the end result is in fact an application that does the things it does well <img src='http://melp.nl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> &#160;<a href="#fnref:2" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2013/01/php-in-the-web-development-world-are-we-doing-it-all-wrong/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tetris in HTML and Javascript</title>
		<link>http://melp.nl/2013/01/tetris-in-html-and-javascript/</link>
		<comments>http://melp.nl/2013/01/tetris-in-html-and-javascript/#comments</comments>
		<pubDate>Wed, 09 Jan 2013 22:43:06 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=731</guid>
		<description><![CDATA[First, I saw the documentary Ecstacy of Order. Then I thought of great things, like building 3D Tetris in HTML5 canvas. I started it, just typing away, of course only Vanilla JS. But after a few hours, having the simple Tetris basics covered, I got bored and stopped. Tetris1 Source at github But wait, there&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>First, I saw the documentary <a href="http://www.imdb.com/title/tt1836974/">Ecstacy of Order</a>. Then I thought of great things, like building 3D Tetris in HTML5 canvas. I started it, just typing away, of course only Vanilla JS. But after a few hours, having the simple Tetris basics covered, I got bored and stopped.</p>

<ul>
<li><a href="http://melp.nl/files/examples/html-tetris">Tetris</a><sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup></li>
<li><a href="http://github.com/drm/html-tetris">Source at github</a></li>
</ul>

<p>But wait, there&#8217;s still hope! I thought I could write a post about me thinking of awesome stuff, getting the basics working and then never finishing it. So I started typing this post, but halfway through, I decided that the basics are good enough. And that the basics are worth posting too.</p>

<p>Sorry if I disappointed you. Have fun reading the code <img src='http://melp.nl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  The gameplay is not that interesting.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>The controls are A &amp; Z for rotating, &lt; and > for moving. You can also use your cursor keys if you use Firefox. Didn&#8217;t test it in IE, btw.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2013/01/tetris-in-html-and-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2: A two piece puzzle.</title>
		<link>http://melp.nl/2012/07/symfony2-a-two-piece-puzzle/</link>
		<comments>http://melp.nl/2012/07/symfony2-a-two-piece-puzzle/#comments</comments>
		<pubDate>Thu, 12 Jul 2012 21:52:21 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[symfony2]]></category>
		<category><![CDATA[varnish]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=677</guid>
		<description><![CDATA[If you&#8217;re getting started with Symfony2, you&#8217;ll get something running pretty quickly. The AcmeBundle contains some of the basic features you&#8217;ll need when writing a Symfony2 app. The basics lie in the MVC paradigm, so there is some model (Doctrine ORM), some view (Twig templates) and some controllers. However, none of that is the real [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re getting started with Symfony2, you&#8217;ll get something running pretty quickly. The AcmeBundle contains some of the basic features you&#8217;ll need when writing a Symfony2 app. The basics lie in the MVC paradigm, so there is some model (Doctrine ORM), some view (Twig templates) and some controllers.</p>

<p>However, none of that is the real core of Symfony2. The most interesting part lies in two main components of the framework. First, the HttpFoundation component and second, the Service container.</p>

<h2>The HTTP Kernel</h2>

<p>Ordinarily, with any controller framework out there, you&#8217;ll have a front controller, a router, a dispatcher and some action controllers that work together to generate output for any URL that is requested within your app. In essence, this is no different in Symfony2. There is something extra though. The HttpKernel, which is actually the core of your application is responsible for speaking HTTP. The developers of Symfony2 have put extra effort into nitpicking every aspect of the protocol, such as caching, so that any application written with the HTTP Component would have all the tools at hand to harness the power of HTTP.</p>

<h3>The request loop</h3>

<p>So, what actually happens when a typical Symfony2 app handles a request, is that a Request object is forged from all PHP&#8217;s relevant variables, it is dispatched into the Kernel as an event. The kernel holds a reference to the service container too. Each of the services registered as an event listener for this particular event is notified, so they can build a response. Then the response triggers a new event so all listeners can influence the response again, and ultimately the Response object is sent to the client.</p>

<p>Both the Request and Response objects reflect HTTP messages. As you probably know, any HTTP message is made up from a status line, a set of headers and an optional body. The headers contain protocol information and the body contains content. Usually, when you visit a page, a GET message is issued to the server, containing some headers on how your browser is configured and what host we want to get the URL from. The webserver responds with an answer, containing a status line which indicates the nature of the rest of the response, headers about the size of the response and some other useful information such as how long the resource may be cached by proxies and browsers, and, finally, a body, usually containing the resource data of the requested object if the request succeeded.</p>

<h3>Parlez-vous HTTP?</h3>

<p>In ye olden days, it was typical for a PHP script to always execute the exact same way, no matter how the user configured their browser or what information on caching was available. Moreover, it was common to have PHP scripts always send, what we affectionately called the &#8220;no cache headers&#8221;, which instructed the browser to absolutely never cache the page and please always come back to refresh the data, so all data was up to date for all PHP pages and all visitors, always. This had also to do with a particular browser that tended to cache more than was actually instructed by the web server, and customers who wanted to see changes rather sooner than later. Well, the conclusion was, that we, as a profession, never learned to <em>parler HTTP</em>.</p>

<p>Nowadays, with applications getting bigger and application speed, performance and stability are makers or breakers of the application&#8217;s success, you&#8217;re soon too late to dive in. There was a few years where we could get away with caching only in the backend by optimizing MySQL&#8217;s query cache, utilizing simple file caching mechanisms or firing up APC, Memcached and all the likes. All very useful, but only half the story.</p>

<h3>Get up `ahhhh! Like a cache-machine</h3>

<p>Basically, there are two ways of caching stuff. You can tell the client to keep a resource a maximum amount of time, or you can tell them when the resource was last modified <sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>. These two models are called Expiration and Validation, respectively.</p>

<p>In the first case, a client may keep the data as long as is specified. In the second case, the client must check back with the server to see if their cached version of the resource is still valid. If not, the response proceeds as usual; if so, the response is set to a 304 Not Modified status and is returned without a body. Expiration and validation can be combined so the client is told how old a resource is and with what frequency they should check back to validate the resource. That&#8217;s the short version. Read the longer version <a href="http://symfony.com/doc/2.0/book/http_cache.html">here</a>.</p>

<h2>The service container</h2>

<p>The service container is a registry. What&#8217;s a registry, you say? It is a container object that contains immutable objects based on unique keys (much like a &#8220;hash&#8221; or a &#8220;map&#8221; structure), which is application wide. Martin Fowler describes it as &#8220;A well-known object that other objects can use to find common objects and services&#8221;<sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup>. The service container itself, therefore, is not that big a deal. THe idea behind it, though, is that all the services that are available in the service container can be loaded on demand. This phenomenon is called lazy loading or bootstrapping. That means that if you have a gazillion services defined, and not one of the lot is used, none of them will be instantiated. This means that if you have a PHP script cropping an image on-the-fly, that does not need the database connection will not open the database connection, <em>even if the script uses the same front controller logic</em>. Now, <em>that</em> sounds like it could be useful.</p>

<h3>Depend this!</h3>

<p>The clever thing about Symfony2&#8242;s service container is that it ships with a load of logic to resolve and inject dependencies. What that means is that if you have, say, a model class which depends on a database connection, you only have to explain to the container how the dependencies can be instantiated and how they reference each other, and the service container will know how to resolve the dependencies. This sounds like a lot of overhead, but as this dependency resolution is done at compile time, and PHP code is generated that actually has all such depencies resolved already, there really is next to none.</p>

<h2>And then?</h2>

<p>Get on the Symfony2-wave. It is rolling like crazy and Github is exploding with bundles (symfony2&#8242;s modules) and contributors. If you know the Kernel and the Dependency Injection components, you should head over to the Form component. Then you know about everything you need to know to build a real Symfony Bundle. The rest will come as you go.</p>

<p>One last tip, don&#8217;t use the Bundle Generator if you don&#8217;t know what it generates and whether you need it or not. Just create your bundle by hand, you can always start generating bundles if you actually know what it does. My next post on this topic will be a simple guide to help set things up by hand in stead of all the command line wizardry. Why? Because then you actually know what the wizard conjures.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>There is also something called &#8220;E-tags&#8221;. In effect, this is the same as a Last-Modified. The semantical difference is that an E-Tag should represent a state of a resource (e.g. a hash, which would of course change as the resource changes) and the Last-Modified always represents a date. The (in)validation works exactly the same.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:2">
<p><a href="http://martinfowler.com/eaaCatalog/registry.html">http://martinfowler.com/eaaCatalog/registry.html</a>&#160;<a href="#fnref:2" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2012/07/symfony2-a-two-piece-puzzle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using a .pfx to install an SSL certificate</title>
		<link>http://melp.nl/2012/07/using-a-pfx-to-install-an-ssl-certificate/</link>
		<comments>http://melp.nl/2012/07/using-a-pfx-to-install-an-ssl-certificate/#comments</comments>
		<pubDate>Sat, 07 Jul 2012 18:38:45 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Linux & BSD]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[ssl]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=703</guid>
		<description><![CDATA[Got a .pfx file and need to install an SSL certificate with this? Here&#8217;s how I did it. You&#8217;ll need to extract the signed public certificate (public key) and the private key without passphrase. cd /etc/nginx/ mkdir ssl cd ssl mv /path/to/pfx/file.pfx . chmod 400 file.fpx First extract the public certificate. You might be asked [...]]]></description>
			<content:encoded><![CDATA[<p>Got a <code>.pfx</code> file and need to install an SSL certificate with this? Here&#8217;s how I did it. You&#8217;ll need to extract the signed public certificate (public key) and the private key without passphrase.</p>

<pre class="shell" style="font-family:monospace;">cd /etc/nginx/
mkdir ssl
cd ssl
mv /path/to/pfx/file.pfx .
chmod 400 file.fpx</pre>

<p>First extract the public certificate. You might be asked for a password.</p>

<pre class="shell" style="font-family:monospace;">openssl pkcs12 -in ./file.pfx -clcerts -nokeys -out public.crt</pre>

<p>And extract the private key:</p>

<pre class="shell" style="font-family:monospace;">openssl pkcs12 -in ./file.pfx -nocerts -nodes -out private.rsa</pre>

<p>Now you can test the server on an arbitrary port, using <code>openssl</code>:</p>

<pre class="shell" style="font-family:monospace;">openssl s_server -www -accept 443 -cert ./public.crt -key ./private.rsa</pre>

<p>Make sure no one can read the files other than you:</p>

<pre class="shell" style="font-family:monospace;">chmod 400 /etc/nginx/ssl/*</pre>

<p>With NginX it is now easy to fire up the server. I used a proxy for this, because from an architecture perspective, this is the easiest:</p>

<pre><code>server {
    server_name example.org;

    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/public.crt;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    location / {
        proxy_pass http://example.org/;
        proxy_set_header Host $host;
        proxy_set_header X-Ssl on;
    }
}
</code></pre>

<p>I pass an additional X-Ssl header to the backend so they know we&#8217;re publicly serving through the SSL proxy (e.g. for building absolute URL&#8217;s). Once you actually know how to do it, it is easy as pie.</p>

<p>With thanks to <a href="http://sycure.wordpress.com/2008/05/15/tips-using-openssl-to-extract-private-key-pem-file-from-pfx-personal-information-exchange/">Yadab Das</a> and <a href="http://stackoverflow.com/questions/403174/convert-pfx-to-cer#answer-405545">Berk D. Demir</a></p>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2012/07/using-a-pfx-to-install-an-ssl-certificate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHPUnit: Closures as dataProviders help with repetitive code</title>
		<link>http://melp.nl/2012/05/phpunit-closures-as-dataproviders-help-with-repetitive-code/</link>
		<comments>http://melp.nl/2012/05/phpunit-closures-as-dataproviders-help-with-repetitive-code/#comments</comments>
		<pubDate>Sun, 13 May 2012 17:20:58 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[FP]]></category>
		<category><![CDATA[phpunit]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=694</guid>
		<description><![CDATA[Since PHP5.3 we have closures. The concept behind closures is unbelievably powerful, and even though PHP has struggled with the concept of typing, callables and whatnot, the main concept of closures remains: passing logic in stead of data, or even: as if it were data. In my previous post I argued that functional and declarative [...]]]></description>
			<content:encoded><![CDATA[<p>Since PHP5.3 we have closures. The concept behind closures is unbelievably powerful, and even though PHP has struggled with the concept of typing, callables and whatnot, the main concept of closures remains: passing logic in stead of data, or even: as if it were data. In my <a href="http://melp.nl/2012/01/declarative-is-the-new-black/">previous post</a> I argued that functional and declarative programming will prevail over pure OO on the long run. This post proves another example of why.</p>

<p><span id="more-694"></span></p>

<p>One simple example of proving closures&#8217; power is in the concept of PHPUnit&#8217;s dataProviders. A data provider provides data to a test, in which a test consumes the data and asserts that the code is ok. As data can also be closures, you can also alter the execution of the tests appropriate to the data you want to test, without actually altering the test. I&#8217;ll show you an example <sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>.</p>

<p>Consider the following class:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> FooBuilder <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> add<span style="color: #009900;">&#40;</span><span style="color: #000088;">$property</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$property</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #000000; font-weight: bold;">function</span> remove<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><a href="http://www.php.net/empty"><span style="color: #990000;">empty</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$property</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <a href="http://www.php.net/array_pop"><span style="color: #990000;">array_pop</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$property</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><a href="http://www.php.net/count"><span style="color: #990000;">count</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$property</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <a href="http://www.php.net/unset"><span style="color: #990000;">unset</span></a><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$property</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #000000; font-weight: bold;">function</span> build<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">properties</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre>

<p>Though there is no obvious use case for this class, the pattern is simple: we have some builder with methods to create something, and the builder provides a <a href="http://martinfowler.com/bliki/FluentInterface.html">fluent interface</a> to do so. This is also very common for query builders, including jQuery. With such a pattern, there is a meriad of possibilities to use this code, with at least as much edge conditions. The order in which the methods are executed might influence the way it is implemented, what would happen if properties are added, removed and then removed again, etc etc.</p>

<p>These edge cases won&#8217;t be displayed by simple use of code coverage, and introducing separate tests for each of these conditions would be cumbersome, having to introduce separate test names for each of the cases.</p>

<p>So, here&#8217;s where closures come in handy. We&#8217;ll simply call the test testBuildingWithFluentInterfaceWillResultInExpectedArray:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> FooBuilderTest <span style="color: #000000; font-weight: bold;">extends</span> \PHPUnit_Framework_TestCase <span style="color: #009900;">&#123;</span>
    <span style="color: #009933; font-style: italic;">/**
     * @dataProvider builderCases
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> testBuildingWithFluentInterfaceWillResultInExpectedArray<span style="color: #009900;">&#40;</span><span style="color: #000088;">$expected</span><span style="color: #339933;">,</span> <span style="color: #000088;">$builderImpl</span><span style="color: #339933;">,</span> <span style="color: #000088;">$description</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$builder</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FooBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assertEquals</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$expectedArray</span><span style="color: #339933;">,</span> <span style="color: #000088;">$builderImpl</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$builder</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #006699; font-weight: bold;">$description</span> failed&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #000000; font-weight: bold;">function</span> builderCases<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
            <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
                <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>FooBuilder <span style="color: #000088;">$builder</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$builder</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
                <span style="color: #0000ff;">&quot;Initial construction&quot;</span>
            <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #666666; font-style: italic;">/* .... */</span>
            <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
                <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'a'</span> <span style="color: #339933;">=&gt;</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'b'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'c'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'x'</span> <span style="color: #339933;">=&gt;</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'y'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'z'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>FooBuilder <span style="color: #000088;">$builder</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$builder</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'a'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'b'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'y'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'z'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'a'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'c'</span><span style="color: #009900;">&#41;</span>
                    <span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
                <span style="color: #0000ff;">&quot;Adding different properties multiple times in a different order&quot;</span>
            <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #666666; font-style: italic;">/* .... */</span>
            <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
                <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>FooBuilder <span style="color: #000088;">$builder</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$builder</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'y'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'z'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">remove</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #009900;">&#41;</span>
                        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">remove</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'x'</span><span style="color: #009900;">&#41;</span>
                    <span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
                <span style="color: #0000ff;">&quot;Adding different properties multiple times in a different order&quot;</span>
            <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
        <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre>

<p>This way, you´ll have a clear view of all the test cases and expected output, without having to only provide data through your data provider, but logic too. Clear separation of use case and consumer logic makes the test very clear and easily extendable.</p>

<p>Hope this offers more food for creativity in your tests <img src='http://melp.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>The example is available as a <a href="https://gist.github.com/2689365">GIST</a>&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2012/05/phpunit-closures-as-dataproviders-help-with-repetitive-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Declarative is the new black.</title>
		<link>http://melp.nl/2012/01/declarative-is-the-new-black/</link>
		<comments>http://melp.nl/2012/01/declarative-is-the-new-black/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 23:34:06 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[FP]]></category>
		<category><![CDATA[languages]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=662</guid>
		<description><![CDATA[The paradigm shift in the purest sense of the expression. The old paradigm makes way for new ones. And declarative is the new one. Well&#8230;, not new new &#8230; The &#8220;old&#8221; paradigm: Procedural Procedural programming is a form of imperative programming in which you define &#8220;procedures&#8221; or &#8220;subroutines&#8221;1 that encapsulate a certain set of operations, [...]]]></description>
			<content:encoded><![CDATA[<p>The paradigm shift in the purest sense of the expression. The old paradigm makes way for new ones. And declarative is the new one. Well&#8230;, not <em>new</em> <a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">new</a> &#8230;
<span id="more-662"></span></p>

<h2>The &#8220;old&#8221; paradigm: Procedural</h2>

<p>Procedural programming is a form of imperative programming in which you define &#8220;procedures&#8221; or &#8220;subroutines&#8221;<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup> that encapsulate a certain set of operations, and accept parameters or &#8220;arguments&#8221; to that set of operations. A very simple example of this, is a procedure that will return the sum of two arguments. In C:</p>

<pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> sum<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> a <span style="color: #339933;">+</span> b<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre>

<p>We declare a procedure that accepts two integer arguments <code>a</code> and <code>b</code> and return an integer sum of the arguments. Simple, efficient, clear. If we want the sum to be present in a third variable, we simply <em>execute</em> the procedure:</p>

<pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> sum<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> a<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> a <span style="color: #339933;">+</span> b<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">*</span>argv<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #993333;">int</span> c<span style="color: #339933;">;</span>
    c <span style="color: #339933;">=</span> sum<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">10</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;c now contains %d<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #808080; font-style: italic;">/* Will output: &quot;c now contains 30&quot; */</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre>

<h3>Procedural is <em>imperative</em></h3>

<p>The procedural style of programming is imperative. Imperative means that you program the execution flow. You decide what pieces of code gets executed by using control structures, loops, procedures, etcetera, and the <em>state</em> of the variables (the &#8220;context&#8221; or &#8220;environment&#8221;) ultimately define the execution flow. This is very intuitive, since you can read most imperative languages as &#8220;if something happens, you do this and that&#8221;. More or less like an instruction video for driving. <q>If someone comes from the right, yield.</q></p>

<h2>The &#8220;newer&#8221; paradigm: Object Oriented</h2>

<p>Another, still imperative, paradigm is Object Oriented programming. Though it is not strictly different from procedural programming, it introduces a new concept: binding data and methods to a single object, that represent one single previously initialized state of the object. This is called instantiation and means that multiple objects of one type can exist in memory simultaneously. Each of these objects have their own methods that act only on the state of that particular object.</p>

<p>There are two concepts that are new in OO style programming, first of which is encapsulation, where the outside world does not need to know what is going on within some object&#8217;s internals. Second is polymorphism, which means that an object can explicitly express that it is capable of some sort of functionality and may implement it in a very different way than another object which exposes the same behaviour. Huh? Bear with me. Here&#8217;s an example.</p>

<pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> AreaCalculator <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">float</span> total <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> add<span style="color: #009900;">&#40;</span>HasArea obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        total <span style="color: #339933;">+=</span> obj.<span style="color: #006633;">getArea</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> subtract<span style="color: #009900;">&#40;</span>HasArea obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        total <span style="color: #339933;">-=</span> obj.<span style="color: #006633;">getArea</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">interface</span> HasArea <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">double</span> getArea<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Arectangle+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Rectangle</span></a> <span style="color: #000000; font-weight: bold;">implements</span> HasArea <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">double</span> _side1<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">double</span> _side2<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Arectangle+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Rectangle</span></a><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">double</span> side1, <span style="color: #000066; font-weight: bold;">double</span> side2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        _side1 <span style="color: #339933;">=</span> side1<span style="color: #339933;">;</span>
        _side2 <span style="color: #339933;">=</span> side2<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">double</span> getArea<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> _side1 <span style="color: #339933;">*</span> _side2<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Circle <span style="color: #000000; font-weight: bold;">implements</span> HasArea <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">double</span> _radius<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> Circle<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">double</span> radius<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        _radius <span style="color: #339933;">=</span> radius<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">double</span> getArea<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amath+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Math</span></a>.<span style="color: #006633;">PI</span> <span style="color: #339933;">*</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amath+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Math</span></a>.<span style="color: #006633;">PI</span> <span style="color: #339933;">*</span> _radius<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Example <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        AreaCalculator calc <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AreaCalculator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// our yard is 10 by 4.2 meters</span>
        calc.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Arectangle+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Rectangle</span></a><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10.0</span>, <span style="color: #cc66cc;">4.2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// But it has a pool, 3 meter in diameter</span>
        calc.<span style="color: #006633;">subtract</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Circle<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1.5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The square metrage we need to buy grass seed for is &quot;</span> <span style="color: #339933;">+</span> calc.<span style="color: #006633;">total</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> 
<span style="color: #009900;">&#125;</span></pre>

<p>The result:</p>

<pre><code>The square metrage we need to buy grass seed for is 27.195593
</code></pre>

<p>The example shows that two different objects have some common characteristic. In this case, they both know how they should produce their own area. The implementation is bound to the meaning of the class itself, since the area of a circle is calculated differently from the area of a rectangle. So, they both provide their own implementation to do so. Since the two different implementations are tightly related, it does make sense that we defined a common interface for it, so the actual consumer of the objects (the calculator) does not need to know they are totally different kinds of objects. All it needs to know is that the object is capable of producing it&#8217;s own area. That&#8217;s it. Well, if you know OO you know this already, but you might not have known that this phenomenon is called <em>polymorphism</em>. The fact that we hide the properties <code>_side1</code>, <code>_side2</code> and <code>_radius</code> from the outside world is <em>encapsulation</em>. Especially polymorphism is something that is hard to achieve with a purely procedural language.</p>

<p>It strikes to see that OO versus procedural, however still imperative, is much more descriptive. It describes natural things in a natural way. A pear is a fruit, an apple is a fruit, they both have some specific characteristics, but they share a lot of common properties and probably operations, such as <code>feed()</code> or <code>ferment()</code>. The programming style still is imperative as it follows the execution flow, but much of the organisation of the code revolves around typing and classifying, so it is more descriptive even though not yet strictly declarative.</p>

<p>It would also appear that OO moves focus from processing and decision-making to behaviour. Describing behaviour is typically part of the object model, because behaviour defines how objects interact and how they depend on each other. This is curious: the data no longer plays the main role in the design of the program, the behaviour does. Let&#8217;s stash that thought.</p>

<h1>Declarative programming</h1>

<p>The main difference between declarative and imperative programming, is that declarative means that you express what something <em>is</em>, rather than what something should <em>do</em>. A common example of declarative programming is build scripts. I&#8217;ll use a Makefile for this example.</p>

<p>As we define a task within a Makefile, we can specify what tasks it is dependent on. As this simply declares what the task does, without actually doing any decision-making within the program this is typically a declarative approach. The tasks get declared as what set of executions the represent. The decisions that are needed to make for execution of the tasks is made by the platform:</p>

<pre class="makefile" style="font-family:monospace;"># building the app depends on mysum.c (the example above)
# if mysum alters, the app should alter too
mysum: mysum.c
    gcc mysum.c -o mysum</pre>

<p>The approach is declarative. We do no checks, we just tell what needs to be done to generate the app. See the entire Makefile for the above examples on <a href="https://github.com/drm/declarative-is-the-new-black/blob/master/Makefile">the github repo</a></p>

<p>Another relatively simple example is Haskell. Without explaining too much about functional programming, the main idea of Haskell is that you declare anything you need. Declaring things does not mean executing them. For example:</p>

<pre class="haskell" style="font-family:monospace;">l <span style="color: #339933; font-weight: bold;">=</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:repeat"><span style="font-weight: bold;">repeat</span></a> <span style="color: red;">5</span></pre>

<p>What happens here is that we declare a list that is made up of an infinite list of 5s. So, how come nothing happens? If the list is infinite, how can it exist? It exists because it is declared. It only gets <em>meaning</em> as soon as it is used in context, which means that the meaning is defined by <em>evaluating</em> the list in it&#8217;s context. When (or even <em>if</em>) this happens. The problem is, imperative programming leads to the assumption that everything that is actually declared, will be evaluated <em>as soon as execution flow enters</em>. This is different in declarative languages, simply because they do not have execution flow. Or, at least, the execution flow is irrelevant. Evaluation is delayed until the point it is required. That is called lazy evaluation. And we like lazy, because lazy means CPU cycles and memory is only consumed as needed.</p>

<h2>The best of both worlds</h2>

<p>Languages now tend to shift to a mixture of (imperative) Object Oriented and (declarative) functional. We see that in Python, Ruby, Erlang and maybe even the best example of them all: Scala. What&#8217;s even more surprising is that in PHP world, which isn&#8217;t the fastest cat of the bunch, the seed is actually planted. Symfony2 introduces declarative paradigms with an <em>inversion of control</em> service container. That is declarative. You simply declare what service depends on another. PHP code is generated to have these dependencies resolve gracefully and lazily and we no longer need to think about execution flow for this. The services and their dependencies are only <em>declared</em>, and the (imperative) code for initializing the services is generated under water. Consequentally, requesting the services from the container will have the services be initialized lazily.</p>

<p>Another fine example is NodeJS. Since the entire model is built around one simple event loop, all behaviour is essentially defined declaratively.</p>

<h2>So, what&#8217;s next?</h2>

<p>Learning imperative languages will become obsolete, just as learning assembly has. You will need to learn how to define behaviour and dependencies, but no longer what needs to be done to get the entire thing rolling. As languages get more and more declarative capabilities and functional programming paradigm features, the imperative idea will only be a resort where the awesomest go.</p>

<p>Or&#8230;. will it? Compiling code introduces overhead. There is no compiler that is able to optimize all and every situation as well as an advanced programmer could. This holds true for, say, a C to Assembly compiler, and would most certainly be the case for compiling declarative approaches. Because ultimately, the little pieces of hardware that get the work done, are not that professed in languages. They only do ones and zeros, and have no concept of meaning. This means that bringing the code from the keyboard to the processor&#8217;s registry will become further and further apart. And if that&#8217;s the case, there&#8217;s only two ways to go. Either software will become even less efficient, or the hardware needs to get smarter. Pick one.</p>

<p><em>NB: The code in this post is on <a href="https://github.com/drm/declarative-is-the-new-black">github</a></em></p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>I&#8217;m purposefully calling these &#8220;procedures&#8221; and not &#8220;functions&#8221;, as functions might confuse with functions in functional programming.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2012/01/declarative-is-the-new-black/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 + PHPCR + Doctrine2 + Jackalope recipe</title>
		<link>http://melp.nl/2011/07/symfony2-phpcr-doctrine2-jackalope-recipe/</link>
		<comments>http://melp.nl/2011/07/symfony2-phpcr-doctrine2-jackalope-recipe/#comments</comments>
		<pubDate>Tue, 26 Jul 2011 21:19:03 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[content repository]]></category>
		<category><![CDATA[doctrine2]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[symfony2]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=644</guid>
		<description><![CDATA[Lately I&#8217;ve followed some developments in the Symfony2 corner of the PHP community with great interest. One of the most enticing developments is the usage of a Content Repository as a backend for your CMS. There is some work being done on the Symfony CMF, combining Symfony2, Doctrine2, PHPCR and Jackalope into a set of [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve followed some developments in the Symfony2 corner of the PHP community with great interest. One of the most enticing developments is the usage of a Content Repository as a backend for your CMS. There is some work being done on the <a href="https://github.com/symfony-cmf/">Symfony CMF</a>, combining <a href="http://symfony.com">Symfony2</a>, <a href="http://doctrine-project.org/">Doctrine2</a>, <a href="https://github.com/phpcr">PHPCR</a> and <a href="https://github.com/jackalope/jackalope">Jackalope</a> into a set of tools for building CMS&#8217;es based on a Content Repository backend. I didn&#8217;t get anything of the CMF to run yet, so I decided to dive in to tying these separate techniques together myself, and get a little proof-of-concept working. <a href="http://github.com/drm/MelpPagesBundle">Here&#8217;s the code</a>, and here&#8217;s the recipe: <span id="more-644"></span></p>

<p>I do not intend to convince you to use a content repository. I think the matters speak for themselves. If you know all the limitations classical setups using relational databases have, you&#8217;ll probably see a future in NoSQL databases, as they are affectionately called. MongoDB and CouchDB never convinced me the way the JCR specification did. Google the specs and read them yourself and know what I mean.</p>

<h2>1. Get a CR backend running</h2>

<p>I chose <a href="http://jackrabbit.apache.org">Apache Jackrabbit</a>, a Java Content Repository (JCR), to do this. As pointed out on the <a href="https://github.com/jackalope">Jackalope</a> website, you&#8217;ll need a patched version of Jackrabbit to get things compatible with PHPCR. Actually, it is just version 2.2 with a backport patch of the 2.3 branch applied to it <sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>, so don&#8217;t fear using it. I&#8217;m told it is pretty stable.</p>

<ol>
<li><a href="http://patched-jackrabbit.s3-website-eu-west-1.amazonaws.com/">Get the patched Jackrabbit here</a>.</li>
<li><p>Run the the server</p>

<pre class="shell" style="font-family:monospace;">java -jar jackrabbit-standalone-*.jar</pre></li>
</ol>

<p>This will run jackrabbit at port 8080. Visit your jackrabbit front end at <a href="http://localhost:8080/">http://localhost:8080/</a>. You&#8217;ll be asked a username and password, but you can leave them blank. By default, there is no access control. If you see a page about jackrabbit, it works.</p>

<h2>2. Install Symfony</h2>

<p>I&#8217;m assuming you know how to do this. If you don&#8217;t, follow <a href="http://symfony.com/doc/current/quick_tour/">the instructions at symfony.com</a>. The short version is:</p>

<ol>
<li><a href="http://symfony.com/download">Download Symfony 2.0 latest version</a></li>
<li>Extract the archive in your document root, say <code>/var/www/</code></li>
<li>Visit <a href="http://localhost/Symfony/web/config.php">/Symfony/web/config.php</a> and follow the instructions</li>
<li>Visit <a href="http://localhost/Symfony/web/app_dev.php">/Symfony/web/app_dev.php</a> to determine if the installation worked</li>
</ol>

<h2>3. Install PHPCR, Jackalope, DoctrinePHPCR ODM and the DoctrinePHPCRBundle</h2>

<p>Go to your <code>vendor</code> dir and clone the PHPCR libraries from github:</p>

<pre class="shell" style="font-family:monospace;">cd /var/www/Symfony/vendor
git clone git://github.com/phpcr/phpcr.git
git clone git://github.com/jackalope/jackalope.git
git clone git://github.com/doctrine/phpcd-odm.git
cd bundles/Symfony/Bundle
git clone git://github.com/symfony-cmf/DoctrinePHPCRBundle.git</pre>

<h2>4. Configure the autoloader</h2>

<p>Open <code>app/autoload.php</code> and configure the namespaces for the downloaded libraries:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #000088;">$loader</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">registerNamespaces</span><span style="color: #009900;">&#40;</span><a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #0000ff;">'Jackalope'</span>             <span style="color: #339933;">=&gt;</span> __DIR__<span style="color: #339933;">.</span><span style="color: #0000ff;">'/../vendor/jackalope/src'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'PHPCR'</span>                 <span style="color: #339933;">=&gt;</span> __DIR__<span style="color: #339933;">.</span><span style="color: #0000ff;">'/../vendor/phpcr/src'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'Doctrine\\ODM\\PHPCR'</span>  <span style="color: #339933;">=&gt;</span> __DIR__<span style="color: #339933;">.</span><span style="color: #0000ff;">'/../vendor/phpcr-odm/lib/'</span><span style="color: #339933;">,</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre>

<h2>5. Add the DoctrinePHPCRBundle to your AppKernel</h2>

<p>Open <code>app/AppKernel.php</code> and add the bundle to the <code>registerBundles()</code> call:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> registerBundles<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$bundles</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #000000; font-weight: bold;">new</span> Symfony\Bundle\DoctrinePHPCRBundle\DoctrinePHPCRBundle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #009900;">&#125;</span></pre>

<h2>6. Configure the ODM default service</h2>

<p>Add the following section to your <code>app/config/config.yml</code> file:</p>

<pre class="yaml" style="font-family:monospace;">doctrine_phpcr:
    session:
        backend:
            url: http://localhost:8080/server/
        workspace: default
        username: ''
        password: ''
    odm:
        auto_mapping: true</pre>

<h2>7. Set up the Doctrine system types</h2>

<p>To have Jackrabbit understand some type internals Doctrine uses for document mapping, we&#8217;ll need to make the content repository aware of these types. There is a console command for that, to make things easy:</p>

<pre class="shell" style="font-family:monospace;">app/console doctrine:phpcr:register-system-node-types</pre>

<p>If you skip this step, persisting documents with a Doctrine DocumentManager will fail with a Jackrabbit error message complaining about <code>phpcr</code> being an unknown namespace.</p>

<h2>8. Set up a PagesBundle</h2>

<p>You should, of course, change the class and namespace names to whatever you wish. Here&#8217;s what I used:</p>

<p>In <code>src/Melp</code>, I created a <a href="http://github.com/drm/MelpPagesBundle">PagesBundle</a>. This bundle will hold my routes for editing, creating, deleting and showing pages from the content repository. It will also hold the Document model classes I will be using for mapping documents to objects:</p>

<pre class="shell" style="font-family:monospace;">cd /var/www/Symfony/src
mkdir -p Melp/PagesBundle/{Controller,Document,Resources{,/views}}</pre>

<p>This creates the bundle&#8217;s directory structure. There is also a console command for it, which can scaffold the directory structure and some classes for you:</p>

<pre class="shell" style="font-family:monospace;">cd /var/www/Symfony
app/console generate:bundle</pre>

<p>The MelpPagesBundle class will be in <code>/var/www/Symfony/src/Melp/PagesBundle/MelpPagesBundle.php</code>, and contains the following code:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">namespace</span> Melp\PagesBundle<span style="color: #339933;">;</span>
&nbsp;
use Symfony\Component\HttpKernel\Bundle\Bundle<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> MelpPagesBundle <span style="color: #000000; font-weight: bold;">extends</span> Bundle <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span></pre>

<p>Add the bundle instance to the AppKernel class&#8217;s bundle initialization routine:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> registerBundles<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$bundles</span> <span style="color: #339933;">=</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #000000; font-weight: bold;">new</span> Melp\Bundle\PagesBundle\MelpPagesBundle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #009900;">&#125;</span></pre>

<h2>9. Set up the controller, routes and view scripts</h2>

<p>I&#8217;ll use Annotations for the controller set up. I was a bit reluctant at first to use annotations for such configuration, but I find it much easier and clear to use annotations than the other configuration options. The only thing we&#8217;ll need is to let the router configuration know the controller exists. We&#8217;ll do that in app/config/routing.yml:</p>

<pre class="yml" style="font-family:monospace;">_pages:
    resource:  &quot;@MelpPagesBundle/Controller/PageController.php&quot;
    type: annotation</pre>

<p>I will also use Twig view scripts. You can of course use PHP view scripts or whatever you prefer, but Twig has had my heart for some time already. The <code>@Template</code> annotation will tell Symfony to render the view resources using the twig template engine as is configured in the default Symfony2 distribution you downloaded. <sup id="fnref:2"><a href="#fn:2" rel="footnote">2</a></sup></p>

<p>The controller class will then look like this:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">namespace</span> Melp\PagesBundle\Controller<span style="color: #339933;">;</span>
&nbsp;
use Symfony\Bundle\FrameworkBundle\Controller\Controller<span style="color: #339933;">;</span>
use Symfony\Component\Routing\Annotation\Route<span style="color: #339933;">;</span>
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PageController <span style="color: #000000; font-weight: bold;">extends</span> Controller
<span style="color: #009900;">&#123;</span>
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/&quot;)
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> indexAction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">redirect</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">generateUrl</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'view'</span><span style="color: #339933;">,</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'path'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'home'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/{path}&quot;, requirements={&quot;path&quot; = &quot;(?!(edit|delete|create)).+&quot;}, name=&quot;view&quot;)
     * @Template
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> viewAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/edit/{path}&quot;, requirements={&quot;path&quot; = &quot;.*&quot;}, name=&quot;edit&quot;)
     * @Template
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> editAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/create/{path}&quot;, requirements={&quot;path&quot; = &quot;.*&quot;}, name=&quot;create&quot;)
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> createAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #009933; font-style: italic;">/**
     * @Route(&quot;/delete/{path}&quot;, requirements={&quot;path&quot; = &quot;.*&quot;}, name=&quot;delete&quot;)
     */</span>
    <span style="color: #000000; font-weight: bold;">function</span> deleteAction<span style="color: #009900;">&#40;</span><span style="color: #000088;">$path</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre>

<p>Since I want to have the routes reflect the path in the content repository, I use a wildcard pattern for the paths, so they may contain slashes. You can use PCRE in your routes, which I used to exclude the <code>/edit</code>, <code>/create</code> and <code>/delete</code> routes from the default <code>viewAction()</code> to avoid conflicts.</p>

<p>These actions will implement CRUD actions for nodes inside the content repository.</p>

<h2>10. Create the document model class</h2>

<p>To have Doctrine manage my model class, I will need to attach Doctrine annotations to it, so Doctrine will know how to read and write model data from and to the content repository backend. I will use a simple Page class, with <code>title</code> and <code>content</code> properties, wich we will later implement the CRUD for, as layed out in the Controller above.</p>

<p>In <code>src/Melp/PagesBundle/Document</code>, create the model reflecting the &#8216;Page&#8217; data structure we&#8217;ll be using to edit and show pages <sup id="fnref:3"><a href="#fn:3" rel="footnote">3</a></sup>.</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">namespace</span> Melp\PagesBundle\Document<span style="color: #339933;">;</span>
&nbsp;
use Doctrine\ODM\PHPCR\Mapping\Annotations <span style="color: #b1b100;">as</span> PHPCRODM<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * @PHPCRODM\Document(alias=&quot;page&quot;)
 */</span>
<span style="color: #000000; font-weight: bold;">class</span> Page
<span style="color: #009900;">&#123;</span>
    <span style="color: #009933; font-style: italic;">/** @PHPCRODM\Id */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$path</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/** @PHPCRODM\String */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$title</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/** @PHPCRODM\String */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$content</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre>

<h2>11. Create a Pages facade and register it as a service</h2>

<p>I created a facade for controlling how pages are persisted and added some logic to that for placing pages in a configured root:</p>

<pre class="yaml" style="font-family:monospace;">services:
    pages:
        class: Melp\PagesBundle\Service\PagesFacade
        arguments:
            - @doctrine_phpcr.odm.default_document_manager
            - 'Melp\PagesBundle\Document\Page'
            - &quot;/pages/&quot;
            - &quot;home&quot;</pre>

<p>The facade exposes the following methods:</p>

<pre><code>public function __construct(\Doctrine\ODM\PHPCR\DocumentManager $dm, $documentClass, $root, $default)
{
}


function createDefault($title = "Homepage")
{
}


function removePath($path)
{
}


function findPath($path)
{
}


function remove($node)
{
}


function persist($node)
{
}
</code></pre>

<p>This saves some clutter in the controller code. The Facade dispatches to the document manager and the document repository for finding and persisting pages.</p>

<h2>12. Create a PageType form class</h2>

<p>Following a best practice not to initialize your forms inside your controller, I created a PageType class in <code>src/Melp/PagesBundle/Form/Type/PageType.php</code>:</p>

<pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">namespace</span> Melp\PagesBundle\Form\Type<span style="color: #339933;">;</span>
&nbsp;
use \Symfony\Component\Form\AbstractType<span style="color: #339933;">;</span>
use \Symfony\Component\Form\FormBuilder<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> PageType <span style="color: #000000; font-weight: bold;">extends</span> AbstractType
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">function</span> buildForm<span style="color: #009900;">&#40;</span>FormBuilder <span style="color: #000088;">$builder</span><span style="color: #339933;">,</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a> <span style="color: #000088;">$options</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$builder</span>
                <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'title'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'text'</span><span style="color: #339933;">,</span> <a href="http://www.php.net/array"><span style="color: #990000;">array</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                <span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'content'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'textarea'</span><span style="color: #009900;">&#41;</span>
        <span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre>

<p>This class will be used inside the controller to build the forms for creating new pages and editing existing ones.</p>

<h2>13. Implement the CRUD Controller</h2>

<p>I chose to implement a very, very basic CRUD for the document class. <a href="https://github.com/drm/MelpPagesBundle/blob/master/Controller/PageController.php">The code</a> speaks for itself. I used <a href="https://github.com/drm/MelpPagesBundle/tree/master/Resources/views/Page">twig templates</a> to render the output of the edit, create and view actions, and rely heavy on flash messages and redirects for feedback to the user.</p>

<h2>Summarizing</h2>

<p>Much, much easier than an RDBMS based hierarchical system of pages, much more convenient and easier to control, and crazily scalable. I think there is much future in this kind of set up. So get comfortable with it while I&#8217;ll do the same, and I hope to get even deeper into the subject some next blog.</p>

<p>I hope this post helped you some further if you got stuck, and is of some inspiration if you want to get started. All tips and comments are appreciated.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p><a href="https://github.com/jackalope/jackalope/wiki/Running-a-jackrabbit-server">https://github.com/jackalope/jackalope/wiki/Running-a-jackrabbit-server</a>&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:2">
<p>See <code>app/config/config.yml</code>, the <code>framework.templating</code> section&#160;<a href="#fnref:2" rev="footnote">&#8617;</a></p>
</li>

<li id="fn:3">
<p>A small introduction is given to this in <a href="[https://github.com/doctrine/phpcr-odm">github.com/doctrine/phpcr-odm</a>&#160;<a href="#fnref:3" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2011/07/symfony2-phpcr-doctrine2-jackalope-recipe/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Failure in a bash script usually means failure of the script</title>
		<link>http://melp.nl/2011/07/failure-in-a-bash-script-usually-means-failure-of-the-script/</link>
		<comments>http://melp.nl/2011/07/failure-in-a-bash-script-usually-means-failure-of-the-script/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 18:49:50 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Linux & BSD]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=632</guid>
		<description><![CDATA[So, when you write a bash script that does a certain amount of tasks for you, but you don&#8217;t want the script to keep running after some command inside the script failed, simply add a line to the script. set -e Quoting the man page: -e errexit Exit immediately if a simple command exits with [...]]]></description>
			<content:encoded><![CDATA[<p>So, when you write a bash script that does a certain amount of tasks for you, but you don&#8217;t want the script to keep running after some command inside the script failed, simply add a line to the script. <span id="more-632"></span></p>

<pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">set</span> <span style="color: #660033;">-e</span></pre>

<p>Quoting the man page:</p>

<blockquote>
  <p><strong><em>-e errexit</em></strong></p>
  
  <p>Exit immediately if a simple command exits with a non-zero, unless the command that fails is part of an until or loop, part of an if statement, part of a &amp;&amp; or || list, if the command&#8217;s return is being inverted using !.</p>
</blockquote>

<p>If you want to reset to normal behaviour, reverse it using:</p>

<pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">set</span> +e</pre>

<p>Very useful, it&#8217;ll save you lot of tedious if&#8217;s and error checking.</p>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2011/07/failure-in-a-bash-script-usually-means-failure-of-the-script/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Apply low priority to low priority processes</title>
		<link>http://melp.nl/2011/07/apply-low-priority-to-low-priority-processes/</link>
		<comments>http://melp.nl/2011/07/apply-low-priority-to-low-priority-processes/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 19:02:59 +0000</pubDate>
		<dc:creator>drm</dc:creator>
				<category><![CDATA[Linux & BSD]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://melp.nl/?p=626</guid>
		<description><![CDATA[My transmission client was hogging my machine. Then I realized I never really use process priorities for CPU and/or IO, which is actually a pretty bad thing, considering some processes just are there to get some job done, but don&#8217;t need priority at all. Then I realized I also never use it for backup and [...]]]></description>
			<content:encoded><![CDATA[<p>My transmission client was hogging my machine. Then I realized I never really use process priorities for CPU and/or IO, which is actually a pretty bad thing, considering some processes just are there to get some job done, but don&#8217;t need priority <em>at all</em>. Then I realized I also never use it for backup and such, which could be a problem for the server I&#8217;m running the backup on. <span id="more-626"></span></p>

<p>I already knew of the <code>nice</code> program, with which you can alter the CPU scheduling prioritization of processes. <code>nice</code> usually prefixes a command to start it up with altered &#8216;niceness&#8217;:</p>

<pre class="shell" style="font-family:monospace;">$ nice -n 19 rsync -a ~ /net/share/backup</pre>

<p><code>renice</code> is used to alter an already running process&#8217;s niceness:</p>

<pre class="shell" style="font-family:monospace;">$ renice -n 19 -p $PID # where, of course $PID is de pid of the process you're altering</pre>

<p>Pretty useful, and also pretty common knowledge, as far as I know. But then it dawned on me that CPU priority isn&#8217;t at all what&#8217;s useful here. You want I/O priority. So, a little googling lead me to <code>ionice</code> &#8211; how inventive a name &#8211; with which you can alter process I/O prioritization. Awesome!</p>

<pre class="shell" style="font-family:monospace;">$ ionice -c 2 -n 4 -p 1234 # Give process 1234 &quot;best effort&quot; priority 4</pre>

<p>You should read the man pages of <code>nice</code> and <code>ionice</code> to find out what the parameters mean (just because it&#8217;s a good habit to read man pages, and not blogs <img src='http://melp.nl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ), but the basic usage is as follows:</p>

<pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># start a process 'some command with arguments' with a niceness of 19. </span>
<span style="color: #666666; font-style: italic;"># 19 means lowest priority, -19 means highest</span>
<span style="color: #c20cb9; font-weight: bold;">nice</span> <span style="color: #660033;">-n</span> <span style="color: #000000;">19</span> some <span style="color: #7a0874; font-weight: bold;">command</span> with arguments 
&nbsp;
<span style="color: #666666; font-style: italic;"># The process with pid 1234 gets a new niceness of 10, provided you are either root,</span>
<span style="color: #666666; font-style: italic;"># or you are the owner of the process</span>
renice <span style="color: #660033;">-n</span> <span style="color: #000000;">10</span> <span style="color: #660033;">-p</span> <span style="color: #000000;">1234</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># The process with pid 1234 gets &quot;Idle&quot; class priority, which means it only gets I/O access</span>
<span style="color: #666666; font-style: italic;"># when no other process needs it.</span>
ionice <span style="color: #660033;">-p</span> <span style="color: #000000;">1234</span> <span style="color: #660033;">-c</span> <span style="color: #000000;">3</span></pre>

<p>Use <code>top</code> and <code>iotop</code> to monitor the usage of CPU and I/O usage respectively. From now on, I&#8217;ll be <em>nice</em> to the kernel and not let him figure out all the prioritization. Wow that&#8217;s cheesy <img src='http://melp.nl/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://melp.nl/2011/07/apply-low-priority-to-low-priority-processes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
