<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
    <channel>
        <title>Whitewashing</title>
        <link>http://www.whitewashing.de/</link>
        <description></description>
        <language>en-us</language>
        <pubDate>Thu, 23 May 2013 00:00:00 +0200</pubDate>
        <item>
            <link>http://www.whitewashing.de/2013/05/23/symfony2_on_windows_azure_websites.html</link>
            <guid>http://www.whitewashing.de/2013/05/23/symfony2_on_windows_azure_websites.html</guid>
            <title><![CDATA[Symfony2 on Windows Azure Websites]]></title>
            <description><![CDATA[<div class="section" id="symfony2-on-windows-azure-websites">
<h1>Symfony2 on Windows Azure Websites</h1>
<p>With the Windows Azure Websites platform-as-a-service (PaaS), which was
released as a preview to a general audiance in June last year, PHP applications
can be deployed to Azure with as much as a Git push to a remote repository. At
the same time Microsoft released a new and much improved <a class="reference external" href="https://github.com/WindowsAzure/azure-sdk-for-php">PHP SDK</a>, which
integrates with all the Azure webservices.</p>
<p>I blogged about deployment with Composer on Azure Websites last November and
since then I have been working with Microsoft to improve Symfony2 support on
Windows Azure by developing and releasing the <a class="reference external" href="https://github.com/beberlei/AzureDistributionBundle">AzureDistributionBundle</a>. This is a new version
of the bundle and contains the following improvements:</p>
<ul class="simple">
<li>Full support for the PHP SDK through the DependencyInjection container</li>
<li>Installation of project dependendencies using Composer during deployment.
I will blog about the Composer support in much more detail in the next
days, because this information is not only valuable for Symfony2 projects.</li>
<li>a <a class="reference external" href="https://github.com/beberlei/symfony-azure-edition">full demo application</a> (derived from
symfony-standard) to show PHP, Symfony &amp; Azure integration</li>
<li>documentation of the Windows Azure Websites deployment process and
possiblities for PHP configuration</li>
<li>a Stream Wrapper for Azure Blob Storage, currently being reviewed for
inclusion into the Azure PHP SDK itself.</li>
</ul>
<p>You can install both the Bundle or the Demo application via Composer.
For the Demo application call:</p>
<div class="highlight-python"><pre>$ php composer.phar create-project beberlei/symfony-azure-edition</pre>
</div>
<p>The README includes more information about how to deploy the demo
to your Azure websites account.</p>
<p>The bundle can be installed using the following <tt class="docutils literal"><span class="pre">composer.json</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">{</span>
    <span class="s">&quot;require&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&quot;beberlei/azure-distribution-bundle&quot;</span><span class="p">:</span> <span class="s">&quot;*&quot;</span>
    <span class="p">},</span>
    <span class="s">&quot;repositories&quot;</span><span class="p">:</span> <span class="p">[</span>
        <span class="p">{</span>
            <span class="s">&quot;type&quot;</span><span class="p">:</span> <span class="s">&quot;pear&quot;</span><span class="p">,</span>
            <span class="s">&quot;url&quot;</span><span class="p">:</span> <span class="s">&quot;http://pear.php.net&quot;</span>
        <span class="p">}</span>
    <span class="p">],</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Registering PEAR is necessary, because the Azure PHP SDK depends on some PEAR
components.</p>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Thu, 23 May 2013 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/04/12/traits_are_static_access.html</link>
            <guid>http://www.whitewashing.de/2013/04/12/traits_are_static_access.html</guid>
            <title><![CDATA[Traits are Static Access]]></title>
            <description><![CDATA[<div class="section" id="traits-are-static-access">
<h1>Traits are Static Access</h1>
<p>In a Twitter discussion yesterday I formulated my negative opinion
about traits and Matthew asked me to clarify it:</p>
<img alt="http://www.whitewashing.de/_static/traits_are_static_access.png" src="http://www.whitewashing.de/_static/traits_are_static_access.png"/>
<p>I used to look forward to traits as a feature in PHP 5.4, but after discussions
with <a class="reference external" href="http://twitter.com/koredn">Kore</a> I came to the conclusion that traits
are nothing else than static access in disguise. They actually lead to the
exact same code smells. Familiar with the outcome of too much static use,
we should reject traits as just another way of statically coupling your code
to other classes.</p>
<p>Let’s step back and take a look at the code smells that Static code produces:</p>
<ul class="simple">
<li>Tight coupling, no way to exchange at runtime</li>
<li>Not mockable</li>
<li>Static code cannot be overwritten through inheritance</li>
<li>Global state (increases likelihood of unwanted side effects)</li>
</ul>
<p>This blog post shows that Traits actually have the first three problems
themselves and exhibit the same code smells. But they even have some additional
problems on their own:</p>
<ul class="simple">
<li>Not testable in isolation</li>
<li>Theoretically stateless, but not enforced in PHP</li>
<li>Very high impact on the code base (Code-Rank)</li>
</ul>
<p>Take the following code, which tries to implement reusable
controller code through traits:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MyController</span>
<span class="p">{</span>
    <span class="k">use</span> <span class="nx">Redirector</span><span class="p">;</span>

    <span class="k">protected</span> <span class="nv">$container</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$container</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span> <span class="o">=</span> <span class="nv">$container</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">someAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">redirect</span><span class="p">(</span><span class="s2">&quot;route_xyz&quot;</span><span class="p">,</span> <span class="k">array</span><span class="p">());</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="nx">trait</span> <span class="nx">Redirector</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">redirect</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nx">RedirectResponse</span><span class="p">(</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">generateUrl</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
        <span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">generateUrl</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'router'</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">generateUrl</span><span class="p">(</span>
            <span class="nv">$routeName</span><span class="p">,</span>
            <span class="nv">$parameters</span>
        <span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Lets spot the problems:</p>
<ol class="arabic">
<li><p class="first"><tt class="docutils literal"><span class="pre">Redirector</span></tt> is tightly coupled to <tt class="docutils literal"><span class="pre">MyController</span></tt>. There is no way to
change this during runtime, by using a different type of redirector, it has
to be exactly the trait used at compile time. This is exactly what static
access enforces as well.</p>
</li>
<li><p class="first">The trait accesses <tt class="docutils literal"><span class="pre">$this-&gt;container</span></tt> without defining it and couples itself against
the implementing classes. We can actually refactor this to include an
abstract method <tt class="docutils literal"><span class="pre">getContainer()</span></tt> in the trait. But if we have multiple
traits now, all having a <tt class="docutils literal"><span class="pre">getContainer()</span></tt> method then we run into method
class problems that cannot be solved. We could pass the container as an
argument to the method, but that actually defeats the purpose of the
abstraction here.</p>
<p>Traits using state of their “parents” usually create bidirectional
coupling between classes, something which should be avoided for good
software design.</p>
</li>
<li><p class="first">No way to overwrite subset of functionality. If I want to use only one
method of a trait and a second one slighty different, then I cannot
overwrite this function of <tt class="docutils literal"><span class="pre">Redirector</span></tt> for example in <tt class="docutils literal"><span class="pre">MyController</span></tt>.</p>
</li>
<li><p class="first">I cannot mock the traits functionality, therefore I cannot test
<tt class="docutils literal"><span class="pre">MyController</span></tt> as a unit only in combination with a trait.</p>
</li>
<li><p class="first">I cannot test the trait as a unit, I always have to create a class
that uses the trait to be able to write a test for it.
This prevents me from testing traits in isolation.</p>
</li>
<li><p class="first">Once you start using <tt class="docutils literal"><span class="pre">Redirector</span></tt> in many controllers, its impact
on your code base (see <a class="reference external" href="http://pdepend.org/documentation/software-metrics/index.html">Code Rank</a>) increases
a lot. Traits are concrete implementations and therefore violate the
Dependency Inversion SOLID principle: Changes in the trait require adoptions
in all the implementing classes.</p>
<p>With aggregation you could depend on an abstraction <tt class="docutils literal"><span class="pre">Redirector</span></tt> or
turn it into an abstraction in the moment that you need different
functionality.</p>
</li>
</ol>
<p>The discovery of this properties of traits me to the conclusion that traits are
just static access in disguise.</p>
<p>To see this argument a bit more drastically, you can “rewrite” a PHP 5.4 trait
into “pseudo” static code:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MyController</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$container</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$container</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span> <span class="o">=</span> <span class="nv">$container</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">someAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nx">Redirector</span><span class="o">::</span><span class="na">redirect</span><span class="p">(</span><span class="s2">&quot;route_xyz&quot;</span><span class="p">,</span> <span class="k">array</span><span class="p">());</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">Redirector</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">redirect</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nx">RedirectResponse</span><span class="p">(</span>
            <span class="nx">self</span><span class="o">::</span><span class="na">generateUrl</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
        <span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">generateUrl</span><span class="p">(</span><span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'router'</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">generateUrl</span><span class="p">(</span>
            <span class="nv">$routeName</span><span class="p">,</span>
            <span class="nv">$parameters</span>
        <span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Calling dynamic methods statically actually works right now (and access to
<tt class="docutils literal"><span class="pre">$this</span></tt> of the parent class will luckily be removed in PHP 5.5). Let’s
reformulate it into something that is actually using static methods and
will work on 5.5, requires changes to the visibility of properties though:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MyController</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$container</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$container</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span> <span class="o">=</span> <span class="nv">$container</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">someAction</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nx">Redirector</span><span class="o">::</span><span class="na">redirect</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="s2">&quot;route_xyz&quot;</span><span class="p">,</span> <span class="k">array</span><span class="p">());</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">Redirector</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">function</span> <span class="nf">redirect</span><span class="p">(</span><span class="nv">$thiz</span><span class="p">,</span> <span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nx">RedirectResponse</span><span class="p">(</span>
            <span class="nx">self</span><span class="o">::</span><span class="na">generateUrl</span><span class="p">(</span><span class="nv">$thiz</span><span class="p">,</span> <span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
        <span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">static</span> <span class="k">function</span> <span class="nf">generateUrl</span><span class="p">(</span><span class="nv">$thiz</span><span class="p">,</span> <span class="nv">$routeName</span><span class="p">,</span> <span class="nv">$parameters</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$thiz</span><span class="o">-&gt;</span><span class="na">container</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'router'</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">generateUrl</span><span class="p">(</span>
            <span class="nv">$routeName</span><span class="p">,</span>
            <span class="nv">$parameters</span>
        <span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Can you see the familiarity? If Traits can be rewritten as calls to static methods,
how can they be any better than static methods? They exhibit the exact same
problems and produce the same code smells.</p>
<p>Conclusion: Traits should be avoided at all costs, just like static methods.</p>
<p>Rule of Thumb: If you want to use a trait, try to think how to solve the
problem with aggregation.</p>
<p>If you want to read more about problems with traits,
<a class="reference external" href="http://blog.ircmaxell.com/2011/07/are-traits-new-eval.html">Anthony</a> wrote
about them quite a while ago.</p>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Fri, 12 Apr 2013 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/04/06/a_failed_side_project.html</link>
            <guid>http://www.whitewashing.de/2013/04/06/a_failed_side_project.html</guid>
            <title><![CDATA[Lessons learned: A failed side project]]></title>
            <description><![CDATA[<div class="section" id="lessons-learned-a-failed-side-project">
<h1>Lessons learned: A failed side project</h1>
<p>Side projects have always been an important part of how I learn new skills and
technologies. This usually ends with me dumping some prototype on <a class="reference external" href="https://github.com/beberlei?tab=repositories">Github</a>, sometimes even with an open
source project that I commit to maintain over a long time.</p>
<p>Two years ago, for the first time, I pursued a project idea which should
not be open-source but a commercial SAAS product. It grew out of the
<a class="reference external" href="http://www.doctrine-project.org">Doctrine</a> teams desire to synchronize
Github Pull Requests with our Jira instance: A workflow engine for HTTP
services. <a class="reference external" href="https://ifttt.com/">If this, then that (IFTTT)</a> already existed at
that point, but was far too limited for my use-case. I wanted something to
allow:</p>
<ul class="simple">
<li>Accept a Github Pull Request Event</li>
<li>Open a Jira Ticket</li>
<li>Comment back on the Pull Request with a link to the Pull Request</li>
<li>Optionally mention that the Pull Request should be made to master, instead of
<tt class="docutils literal"><span class="pre">$BRANCH</span></tt></li>
</ul>
<p>I started developing this in my free time based on PHP, Symfony2, CouchDB,
PostgreSQL and Backbone.js and got a prototype working early. However
instead of reaching the state where I could release the project to others I
hit some hurdles:</p>
<ol class="arabic simple">
<li>The project had a UI where you could add/remove and reconnect tasks through
a graphical workflow editor. The javascript became very messy fast, because
I didn’t understand Backbone fully and also didn’t know patterns for
decoupling and testing Javascript code.</li>
<li>I had to restart with the core domain service side code, because I based it
on the Zeta Components workflow library and it was too unflexible for my
special requirements, messing the code up.</li>
<li>I wanted to implement way too many features and had a huge backlog of
issues to implement before “beta”.</li>
</ol>
<p>Last year in July, when I finally had something remotely usable <a class="reference external" href="https://zapier.com/">Zapier</a> hit the market with a beautiful product and support
for gazillions of services. At that point my service just had support for
Github, Twitter and Jira and for generic HTTP POST requests and a UI that
could not be operated by anyone else but me. I was quite demotivated
that day I found out about Zapier.</p>
<p>Nevertheless I continued to work on the project and tried to make it even more
powerful than Zapier, by introducing more features that neither IFTTT nor
Zapier had. Adding this complexity ended up being the nail into the coffin of
the project.</p>
<p>Each week I worked less and less on the project, because I couldn’t find the
motivation. When Zapier got funded in October I was both sad and happy:
Apparently my idea was a good one, however somebody else executed this idea
much better than myself. I stopped working on the project that week.</p>
<p>Today I took the day to migrate the Doctrine Pull Request workflow to a
<a class="reference external" href="https://github.com/beberlei/githubpr_to_jira">simple hardcoded application</a>
and disabled my projects website entirely.</p>
<p>I want to use this moment to share my personal lessons learned:</p>
<ul>
<li><p class="first">Choosing a scope that allows you to finish a working prototype within 1-2 months
is an important key to success.</p>
<p>The longer it takes to get something working and useable for others, the less
motivation you have. I know from my open-source experience that people using your project
is a huge motivation boost.</p>
<p>The side projects I started since last October are much smaller in scope.</p>
</li>
<li><p class="first">You can actually get burned out by a side project: by designing its scope
way too big.</p>
</li>
<li><p class="first">You cannot compete feature-wise with startups that put their full attention into
a project from morning to night. Either make something small working better
than commercial products or quit your job and put your full time into this.</p>
</li>
<li><p class="first">Side projects are either about learning new technologies or about trying
to build something commercially successful. Don’t try to combine this or
you might get frustrated by choosing the wrong technology for the job.</p>
</li>
<li><p class="first">Never ever use an existing open-source library as the core of your
complicated business domain. If your domain is something remotely interesting
you will fail to achieve your goals with the restrictions of the library.</p>
</li>
<li><p class="first">Starting a big project alone is not a good idea. I found out that
discussing ideas with people is very valuable and at the point where I
started sharing my idea with others I was already too far into the project
to be able to take most of the advice into account.</p>
</li>
<li><p class="first">Keeping a project idea secret is completely useless. Others will come up with the
same idea regardless. People have ideas all the day, however nobody ever has
time to implement them. When they do, execution is even more important than
the idea itself.</p>
</li>
</ul>
<p>What are your lessons learned from failed side projects? I would be happy to
hear other stories.</p>
</div>]]></description>
            <pubDate>Sat, 06 Apr 2013 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/03/12/code_coffee_bonn.html</link>
            <guid>http://www.whitewashing.de/2013/03/12/code_coffee_bonn.html</guid>
            <title><![CDATA[Code & Coffee Bonn]]></title>
            <description><![CDATA[<div class="section" id="code-coffee-bonn">
<h1>Code &amp; Coffee Bonn</h1>
<p>On last years <a class="reference external" href="http://www.socrates-conference.de/">SoCraTes Conference</a> I had
the pleasure to meet <a class="reference external" href="https://twitter.com/sandromancuso">Sandro Mancuso</a> from
the London Software Craftsmanship Community (LSCC). Following his Twitter
account I stumbled upon a meetup concept called “Code &amp; Coffee” which the LSCC
organizes very regularly. At a “Code &amp; Coffee” developers would meet up early
in the morning before work to discuss and hack at some coffee place.</p>
<p>I liked the idea very much and started such an event in Bonn. Our first
test-event was a success, so that we now open up the concept to anyone who
wants to join.</p>
<p>There is a <a class="reference external" href="https://plus.google.com/u/0/communities/118268893445703199868">Google+ Community Code &amp; Coffee Bonn</a> where you can
join and get regular invites to the events.</p>
<p>Our next event is on March 26th. For more details see the Google+ page.</p>
<p>Looking forward to seeing you there!</p>
</div>]]></description>
            <pubDate>Tue, 12 Mar 2013 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/03/04/doctrine_repositories.html</link>
            <guid>http://www.whitewashing.de/2013/03/04/doctrine_repositories.html</guid>
            <title><![CDATA[On Taming Repository Classes in Doctrine]]></title>
            <description><![CDATA[<div class="section" id="on-taming-repository-classes-in-doctrine">
<h1>On Taming Repository Classes in Doctrine</h1>
<p>Over at the <a class="reference external" href="http://drafts.easybib.com/post/44139111915/taiming-repository-classes-in-doctrine-with-the">easybib/dev</a>
Blog Anne posted an entry about their usage of Doctrine Repositories with a
growing amount of query responsibilities. I want to respond to this blog post
with two alternative approaches, because I have seen the easybib approach multiple
times in different projects by different teams and think it can be approved upon a lot.</p>
<p>The problems with the approach outlined are:</p>
<ul>
<li><p class="first">The Repository API does not hide implementation details of the ORM,
the QueryBuilder API is returned to the client code. This might seen
like nitpicking, however it leads to bloated client code doing the
query builder work over and over again. For example the
<tt class="docutils literal"><span class="pre">-&gt;getQuery()-&gt;getSingleResult(AbstractQuery::HYDRATE_ARRAY)</span></tt> call.</p>
</li>
<li><p class="first">Different parts of the QueryBuilder filtering cannot be composed together,
because of the way the API is created. Assume we have the
<tt class="docutils literal"><span class="pre">filterGroupsForApi()</span></tt> call, there is no way to combine it with another
call <tt class="docutils literal"><span class="pre">filterGroupsForPermissions()</span></tt>.  Instead reusing this code will lead
to a third method <tt class="docutils literal"><span class="pre">filterGroupsForApiAndPermissions()</span></tt>.</p>
<p>This can lead to combinatorial explosion of methods that the developer using
the repository needs to know.  And wading through a list of 100 methods to
find the right one is never fun, most importantly when the naming of methods
is imprecise.</p>
</li>
</ul>
<p>Generally introducing a new object such as a repository should pass the
“<a class="reference external" href="http://www.growing-object-oriented-software.com/toc.html">Composite is simpler than the sum of its parts</a>” rule. However the
approach also clearly demonstrates a bad abstraction. In OOP the primary goal is avoiding
changes to affect the whole system.</p>
<div class="section" id="introduce-criteria-objects">
<h2>Introduce Criteria Objects</h2>
<p>Instead of using the <tt class="docutils literal"><span class="pre">QueryBuilder</span></tt> outside of the Repository, lets start with an
alternative refactoring. I will introduce a <tt class="docutils literal"><span class="pre">Criteria</span></tt> class for the <tt class="docutils literal"><span class="pre">User</span></tt>:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserCriteria</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$groupId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$hydrateMode</span> <span class="o">=</span> <span class="nx">Query</span><span class="o">::</span><span class="na">HYDRATE_OBJECT</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>It is important not to introduce a constructor here, because when we add
more and more criterions, the constructor will get bloated. Static
factory methods that create a criteria do make sense however.</p>
<p>Now we can introduce a <tt class="docutils literal"><span class="pre">match</span></tt> method on the <tt class="docutils literal"><span class="pre">UserRepository</span></tt>. Lets see
that on an interface level first, to see how simple usage is for the client
side of the repository:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">UserRepository</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * @param UserCriteria $criteria</span>
<span class="sd">     * @return array&lt;User&gt;|array&lt;array&gt;</span>
<span class="sd">     ***/</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">UserCriteria</span> <span class="nv">$criteria</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Put in a <tt class="docutils literal"><span class="pre">$criteria</span></tt> get back users or array data. Very nice and simple!
The implementation would look like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="sd">/**</span>
<span class="sd"> * @param UserCriteria $criteria</span>
<span class="sd"> * @return array&lt;User&gt;</span>
<span class="sd"> ***/</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">UserCriteria</span> <span class="nv">$criteria</span><span class="p">)</span>
<span class="p">{</span>
    <span class="nv">$qb</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createQueryBuilder</span><span class="p">(</span><span class="s1">'u'</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">groupId</span> <span class="o">!==</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">matchGroup</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$criteria</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">getQuery</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getResult</span><span class="p">(</span><span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">hydrateMode</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">function</span> <span class="nf">matchGroup</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$criteria</span><span class="p">)</span>
<span class="p">{</span>
    <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="s1">'u.group = :group'</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="s1">'group'</span><span class="p">,</span> <span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">groupId</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The benefit here is, that we can add additional conditions and processing
by only adding a new property on the <tt class="docutils literal"><span class="pre">UserCriteria</span></tt> and then handling
this inside <tt class="docutils literal"><span class="pre">UserRepository#match()</span></tt>. Additionally you can save the <tt class="docutils literal"><span class="pre">UserCriteria</span></tt>
in the session, or even in the database to that users can “save filter” or return
to a search overview, with the previous criteria still known.</p>
<p>The client code now looks like:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$criteria</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">UserCriteria</span><span class="p">();</span>
<span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">groupId</span> <span class="o">=</span> <span class="nv">$groupId</span><span class="p">;</span>
<span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">hydrateMode</span> <span class="o">=</span> <span class="nx">Query</span><span class="o">::</span><span class="na">HYDRATE_ARRAY</span><span class="p">;</span>

<span class="nv">$groups</span> <span class="o">=</span> <span class="nv">$app</span><span class="p">[</span><span class="s1">'orm.ems'</span><span class="p">][</span><span class="s1">'api'</span><span class="p">]</span>
    <span class="o">-&gt;</span><span class="na">getRepository</span><span class="p">(</span><span class="s1">'EasyBib\Api\Entity\User'</span><span class="p">)</span>
    <span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$criteria</span><span class="p">);</span>
</pre></div>
</div>
<p>What we achieved in this step, is a simple API for the developer using the
Repository and a simple way to compose conditions by setting new properties
in the criteria.</p>
<p>If you complain that the solution has the same amount of lines, than the
original EasyBib solution, then you are missing the point.  We have factored
away a violation of the Law Of Demeter and calls on an API (Doctrine)
that should be implementation detail of the repository.</p>
<p>Lets try this by adding a new filter criteria, for example permissions I mentioned before:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserCriteria</span>
<span class="p">{</span>
    <span class="k">const</span> <span class="no">PERMISSION_READ</span> <span class="o">=</span> <span class="s1">'read'</span><span class="p">;</span>
    <span class="k">const</span> <span class="no">PERMISSION_WRITE</span> <span class="o">=</span> <span class="s1">'write'</span><span class="p">;</span>
    <span class="c1">//...</span>
    <span class="k">public</span> <span class="nv">$permissions</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">UserRepository</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">UserCriteria</span> <span class="nv">$criteria</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ...</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$criteria</span><span class="o">-&gt;</span><span class="na">permissions</span> <span class="o">!==</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">matchPermissions</span><span class="p">(</span><span class="nv">$criteria</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="c1">// ...</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Simple enough, now we can use it everywhere we want by adding
for example <tt class="docutils literal"><span class="pre">$criteria-&gt;permissions</span> <span class="pre">=</span> <span class="pre">UserCriteria::PERMISSION_WRITE</span></tt>
in our client code.</p>
</div>
<div class="section" id="specification-pattern">
<h2>Specification Pattern</h2>
<p>The Criteria object gets us very far in abstracting lots of query building
behind a very simple API, but it fails short when:</p>
<ul class="simple">
<li>Composing Conditions using combinations of Not/And/Or is not possible
without a tree structure, however <tt class="docutils literal"><span class="pre">Criteria</span></tt> is just a single object.</li>
<li>Removing duplication of code between different repositories. If you
have similar conditions, limit or ordering requirements then you can
only solve this by having all repositories extend a base repository.
But <a class="reference external" href="http://c2.com/cgi/wiki?ImplementationInheritanceIsEvil">Inheritance is evil</a>.</li>
</ul>
<p>The <a class="reference external" href="http://en.wikipedia.org/wiki/Specification_pattern">Specification pattern</a> solves
this issue. There are several ways to implement it, in the spirit of refactoring I will
approach it from our existing Criteria.</p>
<p>Lets move the QueryBuilder code from the repository, into the Criteria object and
rename it <tt class="docutils literal"><span class="pre">UserSpecification</span></tt>. Its important here to change the query builder
code to use expressions that can be composed.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserSpecification</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$groupId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$hydrateMode</span> <span class="o">=</span> <span class="nx">Query</span><span class="o">::</span><span class="na">HYDRATE_OBJECT</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$permissions</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$expr</span> <span class="o">=</span> <span class="s2">&quot;1=1&quot;</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">groupId</span> <span class="o">!==</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$expr</span> <span class="o">=</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">expr</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">and</span><span class="p">(</span><span class="nv">$expr</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">matchGroup</span><span class="p">(</span><span class="nv">$qb</span><span class="p">));</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">permissions</span> <span class="o">!==</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$expr</span> <span class="o">=</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">expr</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">and</span><span class="p">(</span><span class="nv">$expr</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">matchPermissions</span><span class="p">(</span><span class="nv">$qb</span><span class="p">));</span>
        <span class="p">}</span>

        <span class="k">return</span> <span class="nv">$expr</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$query</span><span class="o">-&gt;</span><span class="na">setHydrationMode</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">hydrateMode</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">function</span> <span class="nf">matchGroup</span><span class="p">(</span><span class="nv">$qb</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="s1">'group'</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">groupId</span><span class="p">);</span>

        <span class="k">return</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">expr</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">eq</span><span class="p">(</span><span class="s1">'u.group'</span><span class="p">,</span> <span class="s1">':group'</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">function</span> <span class="nf">matchPermissions</span><span class="p">(</span><span class="nv">$qb</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ...</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The repository is then delegating the expression generation
and puts the result into the <tt class="docutils literal"><span class="pre">where()</span></tt> method of the builder</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserRepository</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">UserSpecification</span> <span class="nv">$specification</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$qb</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createQueryBuilder</span><span class="p">(</span><span class="s1">'u'</span><span class="p">);</span>
        <span class="nv">$expr</span> <span class="o">=</span> <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="s1">'u'</span><span class="p">);</span>

        <span class="nv">$query</span> <span class="o">=</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="nv">$expr</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">getQuery</span><span class="p">();</span>

        <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">modifyQuery</span><span class="p">(</span><span class="nv">$query</span><span class="p">);</span>

        <span class="k">return</span> <span class="nv">$query</span><span class="o">-&gt;</span><span class="na">getResult</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Strictly speaking, the <tt class="docutils literal"><span class="pre">UserSpecification</span></tt> violates the single responsibility
principle, which prevents the composability of specifications and reuse in
different repositories. This is apparent by the <tt class="docutils literal"><span class="pre">$expr</span> <span class="pre">=</span> <span class="pre">&quot;1=1&quot;;</span></tt> line that is
required to make the combination of conditions possible.
Lets factor away the violation of the single
responsibility principle by introducing three specifications:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * @param \Doctrine\ORM\QueryBuilder $qb</span>
<span class="sd">     * @param string $dqlAlias</span>
<span class="sd">     *</span>
<span class="sd">     * @return \Doctrine\ORM\Query\Expr</span>
<span class="sd">     ***/</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">);</span>

    <span class="sd">/**</span>
<span class="sd">     * @param \Doctrine\ORM\Query $query</span>
<span class="sd">     ***/</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">AsArray</span> <span class="k">implements</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$parent</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">Specification</span> <span class="nv">$parent</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">parent</span> <span class="o">=</span> <span class="nv">$parent</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$query</span><span class="o">-&gt;</span><span class="na">setHydrationMode</span><span class="p">(</span><span class="nx">Query</span><span class="o">::</span><span class="na">HYDRATE_ARRAY</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">parent</span><span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">FilterGroup</span> <span class="k">implements</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$group</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$group</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">group</span> <span class="o">=</span> <span class="nv">$group</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="s1">'group'</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">group</span><span class="p">);</span>

        <span class="k">return</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">expr</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">eq</span><span class="p">(</span><span class="nv">$dqlAlias</span> <span class="o">.</span> <span class="s1">'.group'</span><span class="p">,</span> <span class="s1">':group'</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span> <span class="p">{</span> <span class="cm">/* empty ***/</span> <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">FilterPermission</span> <span class="k">implements</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$permissions</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$permissions</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">permissions</span> <span class="o">=</span> <span class="nv">$permissions</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ...</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span> <span class="p">{</span> <span class="cm">/* empty ***/</span> <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now we need a new And-Specification to combine this in our code. This
looks rather abstract and complex on the inside, but for clients
of this object, the usage is simple and obvious.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">AndX</span> <span class="k">implements</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$children</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">children</span> <span class="o">=</span> <span class="nb">func_get_args</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nb">call_user_func_array</span><span class="p">(</span>
            <span class="k">array</span><span class="p">(</span><span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">expr</span><span class="p">(),</span> <span class="s1">'andX'</span><span class="p">),</span>
            <span class="nb">array_map</span><span class="p">(</span><span class="k">function</span> <span class="p">(</span><span class="nv">$specification</span><span class="p">)</span> <span class="k">use</span> <span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">);</span>
            <span class="p">},</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">children</span>
        <span class="p">));</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">foreach</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">children</span> <span class="k">as</span> <span class="nv">$child</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$child</span><span class="o">-&gt;</span><span class="na">modifyQuery</span><span class="p">(</span><span class="nv">$query</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Assuming we import all specifications
from a common namespace <tt class="docutils literal"><span class="pre">Spec</span></tt>, our client code will look
like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$specification</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Spec\AsArray</span><span class="p">(</span><span class="k">new</span> <span class="nx">Spec\AndX</span><span class="p">(</span>
    <span class="k">new</span> <span class="nx">Spec\FilterGroup</span><span class="p">(</span><span class="nv">$groupId</span><span class="p">),</span>
    <span class="k">new</span> <span class="nx">Spec\FilterPermission</span><span class="p">(</span><span class="nv">$permission</span><span class="p">)</span>
<span class="p">));</span>

<span class="nv">$groups</span> <span class="o">=</span> <span class="nv">$app</span><span class="p">[</span><span class="s1">'orm.ems'</span><span class="p">][</span><span class="s1">'api'</span><span class="p">]</span>
    <span class="o">-&gt;</span><span class="na">getRepository</span><span class="p">(</span><span class="s1">'\EasyBib\Api\Entity\Group'</span><span class="p">)</span>
    <span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$specification</span><span class="p">);</span>
</pre></div>
</div>
<p>In contrast to the criteria, we could now implement
or and not specifications to enhance query capabilities.</p>
</div>
<div class="section" id="improving-specifications">
<h2>Improving Specifications</h2>
<p>You can now introduce reusability across different repositories by adding
functionality to check if a specification supports a given entity.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="c1">// ..</span>
    <span class="sd">/**</span>
<span class="sd">     * @param string $className</span>
<span class="sd">     * @return bool</span>
<span class="sd">     ***/</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">supports</span><span class="p">(</span><span class="nv">$className</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Every composite can delegate this operation to its children, and every leaf of
the tree can return true or false. The Repository can then check for a valid
specification in its match method:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">abstract</span> <span class="k">class</span> <span class="nc">EntitySpecificationRepository</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">Specification</span> <span class="nv">$specification</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span> <span class="o">!</span> <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">supports</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getEntityName</span><span class="p">()))</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">\InvalidArgumentException</span><span class="p">(</span><span class="s2">&quot;Specification not supported by this repository.&quot;</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="nv">$qb</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createQueryBuilder</span><span class="p">(</span><span class="s1">'r'</span><span class="p">);</span>
        <span class="nv">$expr</span> <span class="o">=</span> <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="s1">'r'</span><span class="p">);</span>

        <span class="nv">$query</span> <span class="o">=</span> <span class="nv">$qb</span><span class="o">-&gt;</span><span class="na">where</span><span class="p">(</span><span class="nv">$expr</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">getQuery</span><span class="p">();</span>

        <span class="nv">$specification</span><span class="o">-&gt;</span><span class="na">modifyQuery</span><span class="p">(</span><span class="nv">$query</span><span class="p">);</span>

        <span class="k">return</span> <span class="nv">$query</span><span class="o">-&gt;</span><span class="na">getResult</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now we can introduce very generic specifications, such as <cite>OnlyPage($page, Specification $spec)`</cite>
for limit queries, or <tt class="docutils literal"><span class="pre">Equals($field,</span> <span class="pre">$value)</span></tt>. For more readable code, you can then create
a domain language for your specifications that is composed of more simple specifications:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">PowerUsers</span> <span class="k">implements</span> <span class="nx">Specification</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$spec</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">spec</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">OnlyPage</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="k">new</span> <span class="nx">AndX</span><span class="p">(</span>
            <span class="k">new</span> <span class="nx">UsersWithInteraction</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">EnabledUsers</span><span class="p">(),</span>
        <span class="p">));</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">match</span><span class="p">(</span><span class="nx">QueryBuilder</span> <span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">spec</span><span class="o">-&gt;</span><span class="na">match</span><span class="p">(</span><span class="nv">$qb</span><span class="p">,</span> <span class="nv">$dqlAlias</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modifyQuery</span><span class="p">(</span><span class="nx">Query</span> <span class="nv">$query</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">spec</span><span class="o">-&gt;</span><span class="na">modifyQuery</span><span class="p">(</span><span class="nv">$query</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">supports</span><span class="p">(</span><span class="nv">$className</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="p">(</span><span class="nv">$className</span> <span class="o">===</span> <span class="s1">'EasyBib\Api\Entity\User'</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="nv">$top20powerUsers</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Spec\PowerUsers</span><span class="p">();</span>
</pre></div>
</div>
<p>Hiding this kind of composition inside another specification allows
you to reuse query logic in different places in the application
easily and in terms of the domain language.</p>
</div>
<div class="section" id="testability-of-doctrine-repositories">
<h2>Testability of Doctrine Repositories</h2>
<p>One reasons outlined by Anne for this design is testability: Because the
Repository returns the QueryBuilder you have access to the generated SQL.
However testing Doctrine Repositories should never be verifying the generated
SQL. I see a lot of people doing this and it is very fragile and dangerous.
Doctrine is a third party library and as such a rather complex one. Possible
changes that break the test are:</p>
<ul class="simple">
<li>Doctrine adds/removes whitespaces to SQL in a next version</li>
<li>Doctrine performs SQL optimizations in certain cases, the result is the same though.</li>
<li>You add a field/column to any of the tables involved that does not affect the result.</li>
<li>You change something in the Doctrine mapping files, that leads to a reordering of SQL.</li>
</ul>
<p>These are 4 changes that have absolutely nothing to do with the feature you are
actually testing, making the test code very fragile. In terms of abstraction
SQL generation is an implementation detail of the Doctrine ORM and you as
developer are only interested in the public API, which the SQL generation is
not part of.</p>
<p>The code should really be tested against Doctrine itself. Since you are using
Doctrine to get rid of SQL query generation for some use-cases, why should you
use them as measure of quality in your testing efforts.</p>
<p>Testing repositories with the Specification pattern is testing the different
specifications in isolation against a real Doctrine database backend. This will
not be super simple to setup, but the isolation of specifications and their
reusability across repositories actually allows us to keep the number of
tests very small. The pattern avoids the problem of combinatorial explosion of
test-cases very neatly.</p>
<p>The real benefit of testability is achieved in tests of repository client code.
Before we were not able to unit-test this code, because of the Doctrine
EntityManager, Query + QueryBuilder dependencies.  Now We can inject the
repositories into our controllers and services and then use mock objects in the
tests.</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Mon, 04 Mar 2013 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/02/19/extending_symfony2__paramconverter.html</link>
            <guid>http://www.whitewashing.de/2013/02/19/extending_symfony2__paramconverter.html</guid>
            <title><![CDATA[Extending Symfony2: ParamConverter]]></title>
            <description><![CDATA[<div class="section" id="extending-symfony2-paramconverter">
<h1>Extending Symfony2: ParamConverter</h1>
<p>Symfony2 is an extremely extendable framework, everything is extendable or
overwritable through the Dependency Injection Container. The problem developers
face is knowing about the extension points and when to use them.  If you don’t
know the extension points, your Symfony application will end up with code
duplication, too much inheritance and very little unit-testable code.</p>
<p>This blog post will be the first in a series, describing Symfony2 extension
points that help you achieve clean and duplicateless code. In my experience,
using Symfony extension points to avoid code duplication helps you avoid
writing thousands of lines of code in your controllers.</p>
<div class="section" id="the-problem-duplicate-finder-logic">
<h2>The problem: Duplicate finder logic</h2>
<p>Inside controllers you can easily end with lots of duplication using the same
general finder logic again in several actions. Take this following example:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">(</span><span class="nv">$id</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$dql</span> <span class="o">=</span> <span class="s2">&quot;SELECT u, d, a</span>
<span class="s2">                  FROM MyBundle\Entity\User u</span>
<span class="s2">                  JOIN u.details d</span>
<span class="s2">                  JOIN u.addresses a</span>
<span class="s2">                  WHERE u.id = ?1&quot;</span><span class="p">;</span>

        <span class="nv">$user</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'doctrine.orm.default_entity_manager'</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">createQuery</span><span class="p">(</span><span class="nv">$dql</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nv">$id</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">getSingleResult</span><span class="p">();</span>

        <span class="k">if</span> <span class="p">(</span> <span class="o">!</span> <span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">NotFoundHttpException</span><span class="p">();</span>
        <span class="p">}</span>

        <span class="k">return</span> <span class="k">array</span><span class="p">(</span><span class="s1">'user'</span> <span class="o">=&gt;</span> <span class="nv">$user</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If we need this block of code in several actions of different controllers, we
will end up with duplication that has to be eliminated.</p>
</div>
<div class="section" id="the-quick-and-dirty-solution">
<h2>The Quick and Dirty Solution</h2>
<p>One way of resolving the duplication appearing in this case, is moving the
finder + not found logic into a common controller base class or into a trait.
But this leaves us with a helper method buried in the code and a static
dependency to a base class or a trait that we want to avoid.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">AbstractController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">function</span> <span class="nf">findUser</span><span class="p">(</span><span class="nv">$id</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$dql</span> <span class="o">=</span> <span class="s2">&quot;SELECT u, d, a</span>
<span class="s2">                  FROM MyBundle\Entity\User u</span>
<span class="s2">                  JOIN u.details d</span>
<span class="s2">                  JOIN u.addresses a</span>
<span class="s2">                  WHERE u.id = ?1&quot;</span><span class="p">;</span>

        <span class="nv">$user</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'doctrine.orm.default_entity_manager'</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">createQuery</span><span class="p">(</span><span class="nv">$dql</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nv">$id</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">getSingleResult</span><span class="p">();</span>

        <span class="k">if</span> <span class="p">(</span> <span class="o">!</span> <span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">NotFoundHttpException</span><span class="p">();</span>
        <span class="p">}</span>

        <span class="k">return</span> <span class="nv">$user</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There are two problems with this sort of refactoring:</p>
<ol class="arabic simple">
<li>We are using inheritance for code-reuse.</li>
<li>We hide the <tt class="docutils literal"><span class="pre">findUser</span></tt> behavior in an abstract class and make it hard to test.</li>
</ol>
</div>
<div class="section" id="the-preferred-solution">
<h2>The Preferred Solution</h2>
<p>The <a class="reference external" href="http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html">SensioFrameworkExtraBundle</a>
offers an extension hook called <strong>Parameter Converters</strong> to transform Request
attributes to objects directly for controller method arguments. They hook into
the <tt class="docutils literal"><span class="pre">kernel.controller</span></tt> event that you can use yourself to achieve the same
goal.</p>
<p>Lets see how the action will look like after our refactoring:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">UserController</span> <span class="k">extends</span> <span class="nx">Controller</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">(</span><span class="nx">User</span> <span class="nv">$user</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">array</span><span class="p">(</span><span class="s1">'user'</span> <span class="o">=&gt;</span> <span class="nv">$user</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Very concise and easy to read. The param converter doing the heavy lifting
looks like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">namespace</span> <span class="nx">MyProject\Request\ParamConverter</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationInterface</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Symfony\Component\HttpFoundation\Request</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Symfony\Component\HttpKernel\Exception\NotFoundHttpException</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Doctrine\ORM\EntityManager</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">UserParamConverter</span> <span class="k">implements</span> <span class="nx">ParamConverterInterface</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$entityManager</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nx">EntityManager</span> <span class="nv">$entityManager</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">entityManager</span> <span class="o">=</span> <span class="nv">$entityManager</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">apply</span><span class="p">(</span><span class="nx">Request</span> <span class="nv">$request</span><span class="p">,</span> <span class="nx">ConfigurationInterface</span> <span class="nv">$configuration</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$id</span> <span class="o">=</span> <span class="nv">$request</span><span class="o">-&gt;</span><span class="na">attributes</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'id'</span><span class="p">);</span>

        <span class="nv">$dql</span> <span class="o">=</span> <span class="s2">&quot;SELECT u, d, a</span>
<span class="s2">                  FROM MyBundle\Entity\User u</span>
<span class="s2">                  JOIN u.details d</span>
<span class="s2">                  JOIN u.addresses a</span>
<span class="s2">                  WHERE u.id = ?1&quot;</span><span class="p">;</span>

        <span class="nv">$user</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'doctrine.orm.default_entity_manager'</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">createQuery</span><span class="p">(</span><span class="nv">$dql</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">setParameter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nv">$id</span><span class="p">)</span>
            <span class="o">-&gt;</span><span class="na">getSingleResult</span><span class="p">();</span>

        <span class="k">if</span> <span class="p">(</span> <span class="o">!</span> <span class="nv">$user</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">NotFoundHttpException</span><span class="p">();</span>
        <span class="p">}</span>

        <span class="nv">$param</span> <span class="o">=</span> <span class="nv">$configuration</span><span class="o">-&gt;</span><span class="na">getName</span><span class="p">();</span>
        <span class="nv">$request</span><span class="o">-&gt;</span><span class="na">attributes</span><span class="p">(</span><span class="nv">$param</span><span class="p">,</span> <span class="nv">$user</span><span class="p">);</span>

        <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">supports</span><span class="p">(</span><span class="nx">ConfigurationInterface</span> <span class="nv">$configuration</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="s2">&quot;MyProject\Entity\User&quot;</span> <span class="o">===</span> <span class="nv">$configuration</span><span class="o">-&gt;</span><span class="na">getClass</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now we only need to register this class in the dependency injection container:</p>
<div class="highlight-xml"><div class="highlight"><pre><span class="nt">&lt;service</span> <span class="na">id=</span><span class="s">&quot;my_project.user_param_converter&quot;</span>
      <span class="na">class=</span><span class="s">&quot;MyProject\Request\ParamConverter\UserParamConverter&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;argument</span> <span class="na">type=</span><span class="s">&quot;service&quot;</span> <span class="na">id=</span><span class="s">&quot;doctrine.orm.default_entity_manager&quot;</span> <span class="nt">/&gt;</span>

    <span class="nt">&lt;tag</span> <span class="na">name=</span><span class="s">&quot;request.param_converter&quot;</span> <span class="na">converter=</span><span class="s">&quot;user&quot;</span> <span class="na">priority=</span><span class="s">&quot;10&quot;</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/service&gt;</span>
</pre></div>
</div>
<p>With the priority configuration the <tt class="docutils literal"><span class="pre">User</span></tt> entity is now always handled
by our custom param converter and not by the default Doctrine converter.</p>
<p>In a next step, we should extract the query logic from the ParamConverter
into a custom Doctrine entity repository. But that is a task for another blog
post in this series.</p>
</div>
</div>]]></description>
            <category><![CDATA[ Symfony2 ]]></category>
            <pubDate>Tue, 19 Feb 2013 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2013/02/04/doctrine_and_solid.html</link>
            <guid>http://www.whitewashing.de/2013/02/04/doctrine_and_solid.html</guid>
            <title><![CDATA[Doctrine and SOLID]]></title>
            <description><![CDATA[<div class="section" id="doctrine-and-solid">
<h1>Doctrine and SOLID</h1>
<p>I often get asked how you can use <a class="reference external" href="http://www.doctrine-project.org">Doctrine2</a> and implement <a class="reference external" href="http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)">the SOLID principles</a> at the same
time. It bugs me having to reply: It is not really possible.  Because Doctrine2
does not support value-objects (or embedded-objects), it is very hard to pull
the <a class="reference external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> off.</p>
<p>These problems are related to the inability to share behavioral code through
aggregation and the complexity of state transformations. Combining both, your
average entity with 5-15 fields can end up with hundreds or thousands lines of
code. The solutions to both problems boil down to <a class="reference external" href="http://www.jbrains.ca/permalink/the-four-elements-of-simple-design">minimizing duplication and
maximizing clarity</a>.</p>
<div class="section" id="extracting-value-objects-minimize-duplication">
<h2>Extracting Value Objects: Minimize Duplication</h2>
<p>Entity classes responsibility are the state transformations of their internal
fields.  This can simply be done by using setter methods or <a class="reference external" href="http://whitewashing.de/2012/08/22/building_an_object_model__no_setters_allowed.html">when avoiding
setters</a>,
with use-case driven methods.  These state transformations can be part of
different responsibilities, specifically when properties belong to different
groups of concepts.</p>
<p>Take a very simple entity that contains updated/created at logic:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">use</span> <span class="nx">Doctrine\ORM\Mapping</span> <span class="k">as</span> <span class="nx">ORM</span><span class="p">;</span>

<span class="sd">/**</span>
<span class="sd"> * @ORM\Entity</span>
<span class="sd"> * @ORM\HasLifecycleCallbacks</span>
<span class="sd"> **/</span>
<span class="k">class</span> <span class="nc">Person</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * @ORM\Column(type=&quot;datetime&quot;)</span>
<span class="sd">     **/</span>
    <span class="k">private</span> <span class="nv">$createdAt</span><span class="p">;</span>
    <span class="sd">/**</span>
<span class="sd">     * @ORM\Column(type=&quot;datetime&quot;)</span>
<span class="sd">     **/</span>
    <span class="k">private</span> <span class="nv">$updatedAt</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createdAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">updatedAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="sd">/**</span>
<span class="sd">     * @ORM\PreUpdate</span>
<span class="sd">     **/</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">updatedAt</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">updatedAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If you want to duplicate this logic to another second entity, then in Doctrine
the solution for this is using traits. <a class="reference external" href="http://kore-nordmann.de/blog.html">Kore</a> will dismiss this solution, because
traits create a hard dependency. Even if we accept the static dependency,
traits are not perfect even for this very simple example, because its very
likely that you cannot override the constructor of every entity.</p>
<p>The solution is to extract a value object <tt class="docutils literal"><span class="pre">Timestamped</span></tt> that contains
all the logic:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Timestamped</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$createdAt</span><span class="p">;</span>
    <span class="k">private</span> <span class="nv">$updatedAt</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createdAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">updatedAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">updatedAt</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">updatedAt</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">Person</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$timestamped</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">timestamped</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Timestamped</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>See how all the code could be moved into <tt class="docutils literal"><span class="pre">Timestamped</span></tt> and is now reusable
in other entities.</p>
<p>Doctrine has no support for embedded objects, which is very sad. I am working
very hard to get this feature into Doctrine as soon as possible. You can use
the “object” type as a workaround and <tt class="docutils literal"><span class="pre">serialize()</span></tt> the value object into
the database. However this is beyond ugly in my opinion.</p>
</div>
<div class="section" id="extract-method-objects-maximizing-clarity">
<h2>Extract Method Objects: Maximizing clarity</h2>
<p>Once you have identified groups of fields that are modified, then the
complexity of the state transformations can attract lots of code.</p>
<p>Take an <tt class="docutils literal"><span class="pre">Order</span></tt> object that has a method for calculating the shipping costs,
depending all the order items and products.
To separate calculations from state transformations you can extract
method objects instead of inlining the code into the <tt class="docutils literal"><span class="pre">Order</span></tt> object.</p>
<p>For this kind of extraction I create a folder <tt class="docutils literal"><span class="pre">Order</span></tt> and put all
the extracted method objects in the <tt class="docutils literal"><span class="pre">Order</span></tt> subnamespace.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">namespace</span> <span class="nx">MyProject\Entity</span> <span class="p">{</span>

    <span class="k">class</span> <span class="nc">Order</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">calculateShippingCosts</span><span class="p">()</span>
        <span class="p">{</span>
            <span class="nv">$calculator</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ShippingCostCalculator</span><span class="p">();</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">shippingCosts</span> <span class="o">=</span> <span class="nv">$calculator</span><span class="o">-&gt;</span><span class="na">calculate</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">namespace</span> <span class="nx">MyProject\Entity\Order</span> <span class="p">{</span>

    <span class="k">class</span> <span class="nc">ShippingCostCalculator</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">calculate</span><span class="p">(</span><span class="nx">Order</span> <span class="nv">$order</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>From this step its easy to make the code reusable by passing the shipping cost
calculator:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Order</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">calculateShippingCosts</span><span class="p">(</span><span class="nx">ShippingCostCalculator</span> <span class="nv">$calculator</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">shippingCosts</span> <span class="o">=</span> <span class="nv">$calculator</span><span class="o">-&gt;</span><span class="na">calculate</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Another benefit is that you can test the shipping cost calculator directly in a
unit-test and avoid checking for the correctness indirectly through a getter
method for the shipping costs.</p>
<p>Extracting every method of an entity into a method object is obviously
overkill. You should exercise caution and common sense when performing this
refactoring.</p>
</div>
<div class="section" id="conclusion">
<h2>Conclusion</h2>
<p>Not all the techniques to implement SOLID code can be exploited when using Doctrine
for technical reasons. In the future I hope to support value objects in
Doctrine to make this possible.</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Mon, 04 Feb 2013 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/11/19/composer_and_azure_websites_git_deployment.html</link>
            <guid>http://www.whitewashing.de/2012/11/19/composer_and_azure_websites_git_deployment.html</guid>
            <title><![CDATA[Composer and Azure Websites Git Deployment]]></title>
            <description><![CDATA[<div class="section" id="composer-and-azure-websites-git-deployment">
<h1>Composer and Azure Websites Git Deployment</h1>
<p>Continuing my series on PHP PaaS Clouds (<a class="reference external" href="http://fortrabbit.com/">Fortrabbit</a>), I turn to Microsoft Azure today. After some
research I found out Azure supports post deployment hooks to run
Composer and allows you to configure environment variables from the Management
console.</p>
<p>Microsoft launched <a class="reference external" href="https://www.windowsazure.com/en-us/home/scenarios/web-sites/">Azure Websites</a> in June this
year.  It is a platform as a service solution where you can deploy your
websites via FTP or Git. With Azure Websites you can avoid having to deal with
the complex deployment automation that is necessary for <a class="reference external" href="https://www.windowsazure.com/en-us/home/features/cloud-services/">Azure Hosted Cloud
Services</a>.
As long as your website only requires an SQLServer, MySQL or external APIs you
can actually achieve quite a lot already.</p>
<p>For a <a class="reference external" href="http://www.symfony.com">Symfony2</a>, <a class="reference external" href="http://www.silex-project.org">Silex</a> or any other modern project however you want
<a class="reference external" href="http://www.getcomposer.org">Composer</a> support during the deployment as
long as failures with Composer don’t break your site.</p>
<p>It turns out that Azure Websites - to support other platforms that require
compiling - actually has an extremely robust deployment system (as far as I
understood its internals). The Git repository is separated from the actual code
that is served from the webserver and a number of old checkouts is kept to
allow rollbacks through the Web interface. Once a Git push was recognized,
Azure websites will execute a build step, and then copy all the files over to a
directory with the name of the Git SHA hash. This directory is then symlinked
to the document root.</p>
<p>If Composer fails during this step, the website will still be served from the
currently running version and you don’t have to face unexpected downtime.</p>
<p>To actually run Composer as a post-deployment tool you have to do some manual
work. Create a <tt class="docutils literal"><span class="pre">.deployment</span></tt> file in your project root folder:</p>
<div class="highlight-ini"><div class="highlight"><pre><span class="k">[config]</span>
<span class="na">command</span> <span class="o">=</span> <span class="s">&quot;D:\Program Files (x86)\PHP\v5.3\php.exe&quot; build_azure.php</span>
</pre></div>
</div>
<p>If you are using PHP 5.4, then you probably have to change the command version
name to “v5.4”, but I haven’t tested this.</p>
<p>Then you need to create the <tt class="docutils literal"><span class="pre">build_azure.php</span></tt> file that is referenced in the
deployment command. The actual implementation is up to you, my version is
the most simple one:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nb">file_exists</span><span class="p">(</span><span class="s2">&quot;composer.phar&quot;</span><span class="p">))</span> <span class="p">{</span>
    <span class="nv">$url</span> <span class="o">=</span> <span class="s1">'https://getcomposer.org/composer.phar'</span><span class="p">;</span>
    <span class="nb">file_put_contents</span><span class="p">(</span><span class="s2">&quot;composer.phar&quot;</span><span class="p">,</span> <span class="nb">file_get_contents</span><span class="p">(</span><span class="nv">$url</span><span class="p">));</span>
<span class="p">}</span>

<span class="nv">$_SERVER</span><span class="p">[</span><span class="s1">'argv'</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;update&quot;</span><span class="p">;</span>
<span class="nv">$_SERVER</span><span class="p">[</span><span class="s1">'argv'</span><span class="p">][</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;--prefer-dist&quot;</span><span class="p">;</span>
<span class="nv">$_SERVER</span><span class="p">[</span><span class="s1">'argv'</span><span class="p">][</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;-v&quot;</span><span class="p">;</span>
<span class="k">require</span> <span class="s2">&quot;composer.phar&quot;</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This currently only works with a Composer version, where
<a class="reference external" href="https://github.com/composer/composer/pull/1341">PR-1341</a> is applied.
You can check out <a class="reference external" href="https://github.com/beberlei/composer/tree/GH-1339">my Composer fork</a> and run
<tt class="docutils literal"><span class="pre">./bin/compile</span></tt> to generate a composer.phar that works.</p>
</div>
<p>Instead of using this approach, you could ship <tt class="docutils literal"><span class="pre">composer.phar</span></tt> with your repository for example.
You can of course execute additional steps in the <tt class="docutils literal"><span class="pre">build_azure.php</span></tt>, for example warmup caches.</p>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Mon, 19 Nov 2012 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/10/27/babysteps_with_fortrabbit_php_cloud.html</link>
            <guid>http://www.whitewashing.de/2012/10/27/babysteps_with_fortrabbit_php_cloud.html</guid>
            <title><![CDATA[Babysteps with Fortrabbit PHP Cloud]]></title>
            <description><![CDATA[<div class="section" id="babysteps-with-fortrabbit-php-cloud">
<h1>Babysteps with Fortrabbit PHP Cloud</h1>
<p>I wanted to host a simple application to play around with the <a class="reference external" href="https://tent.io">Tent Protocol</a> (see <a class="reference external" href="http://whitewashing.de/2012/10/22/a_tent_io_app__zelten_bookmarks.html">my last blogpost</a>), so
I checked through some of the PHP Cloud providers again for the fun of it. One
requirement was to deploy from Git and update dependencies from Composer. I
found a new provider that i haven’t heard of before, <a class="reference external" href="http://www.fortrabbit.com/">Fortrabbit</a> that supports this so I had to check it out.
It has some more features that I really dig:</p>
<p>Fortrabbit provides you with a Git url where you can push your repository.
It is directly deployed during the push operation. You can trigger composer
updates by having a special syntax in the commit message. The push
output informs you about all the steps performed during deployment.</p>
<p>Additionally you can configure environment variables in the web-administration
interface that are available in the application through <tt class="docutils literal"><span class="pre">$_SERVER</span></tt>. You
can easily use them to configure your application, if its hosted in a public
repository. Great to share sample applications on Github and host them from
there.</p>
<p>You get SSH access to the machines, where you can take a look at the apache
and php error log files. You have vim available. Quite cool and very helpful
for any kind of debugging necessary. Deployments overwrite every change you
make, so its still a save environment.</p>
<p>The composer support allows for post install scripts, which is cool to perform
all sorts of cache warmup and other deployment tasks.</p>
<p>You can host one application for free, however they shutdown after 48 hours if
you don’t regularly click on a reset button. Its definitely enough to get small
prototypes up and running. From there you can upgrade in many small steps from
small plans (10€/month) to bigger ones (80€/month).</p>
</div>]]></description>
            <pubDate>Sat, 27 Oct 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/10/22/a_tent_io_app__zelten_bookmarks.html</link>
            <guid>http://www.whitewashing.de/2012/10/22/a_tent_io_app__zelten_bookmarks.html</guid>
            <title><![CDATA[A tent.io app: Zelten Bookmarks]]></title>
            <description><![CDATA[<div class="section" id="a-tent-io-app-zelten-bookmarks">
<h1>A tent.io app: Zelten Bookmarks</h1>
<p>Over the weekend I built a <a class="reference external" href="http://zelten.eu1.frbit.net">very simple bookmarking application</a> for <a class="reference external" href="http://tent.io">tent.io</a>. I wanted to try the tent functionality to create
arbitrary entities of data using something as simple as a “Bookmark”.</p>
<p>The application retrieves and stores bookmarks on your own tent-server, nothing
is kept on the applications server and as a user you keep full control over
your content (bookmarks).</p>
<p>The <a class="reference external" href="https://github.com/beberlei/zelten-bookmarks">code for the application</a>
is on Github, as well as the <a class="reference external" href="https://github.com/beberlei/TentPHP">TentPHP library</a> I have written to support the protocol.
The application is using PHP, the Silex microframework and MySQL.</p>
<div class="section" id="so-what-is-tent-and-why-bother">
<h2>So what is Tent and why bother?</h2>
<p>About two month ago a new distributed social networking protocol was launched called
<a class="reference external" href="http://tent.io">Tent.io</a>. It works over HTTP using JSON and distributes data
using webhooks. This happened in the shadow of <a class="reference external" href="http://www.app.net">app.net</a>
funding, just two weeks after they collected over 500k USD. Tent.io got lots of
attention but not as much as app.net sadly. Its distributed nature however is
much more suited to achieving true independence of large companies and true privacy
for the users though. Compared to Diaspora it has the benefit of being a protocol, not
an application first.</p>
<p>Now two month later, there are <a class="reference external" href="https://github.com/tent">reference implementations</a>
for Server, Client and a Twitter like Status application. You can use <a class="reference external" href="http://tent.is">Tent.is</a> to create a free or payed tent account including access to
the status application or setup your own tentd server on Heroku.</p>
<p>As a user I can connect any application to the tent server I have registered
with and control the visibility and sharing policies. Content can be private,
public or visible to certain groups only. A Tent server then makes sure to
distribute content to the appropriate subscribers.</p>
<p>In this early state of the protocol it makes sense to register on the central
tent.is service, however when the server gets more stable or alternative
server implementations popup its easy to move all your data off tent.is to your
own server. One feature that will hit tent.is soonish is registration of domain
records. That will be the first step to your own tent server, I am eagerly
waiting to host all my content at <a class="reference external" href="https://tent.beberlei.de">https://tent.beberlei.de</a> at some day.</p>
</div>
<div class="section" id="tent-io-sounds-awesome-how-can-i-help">
<h2>Tent.io sounds awesome, how can I help?</h2>
<p>Right at the moment the tent software stack is developed by the team that also
hosts <a class="reference external" href="https://tent.is">Tent.is</a>. If all you can provide is money, then
signing up for the 12 USD per month is the way to go.</p>
<p>If you are a developer, then take a look at the <a class="reference external" href="https://github.com/tent/tent.io/wiki/Related-projects">Wiki</a> where related
projects are listed. You will find a bunch of client libraries for major
languages already, helping you to get started.</p>
<p>I suppose the major work lies in implementing Status-Post clients for all
major smartphone platforms and desktops. As well as the host of applications
that Facebook and other social networks provides:</p>
<ul class="simple">
<li>Manage and share Photo albums</li>
<li>Plan and share events</li>
<li>Managing contact data/address book</li>
<li>Resume details (Linkedin/Xing)</li>
<li>Track User Events (Timeline)</li>
<li>Sharing Music and Videos (Myspace)</li>
<li>Importing all sorts of existing content (RSS,..)</li>
</ul>
</div>
</div>]]></description>
            <pubDate>Mon, 22 Oct 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/09/04/using_assertions_for_validation.html</link>
            <guid>http://www.whitewashing.de/2012/09/04/using_assertions_for_validation.html</guid>
            <title><![CDATA[Using Assertions for validation]]></title>
            <description><![CDATA[<div class="section" id="using-assertions-for-validation">
<h1>Using Assertions for validation</h1>
<p>We all know PHP is weakly typed and has some weird type-conversion rules.
This can often complicate our code checking for invalid or illegal data.
Using if/else clauses we can do all sorts of validation, but with standard
coding styles (PSR, Zend, PEAR) we end up with at least 3 lines per check,
cluttering the whole code-base.</p>
<p>Take <a class="reference external" href="http://phpazure.codeplex.com/SourceControl/changeset/view/67037#840935">this example</a> from
the old deprecated Windows Azure SDK, a method for putting a binary file into
Azures blob storage:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">putBlob</span><span class="p">(</span><span class="nv">$containerName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$blobName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$localFileName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$metadata</span> <span class="o">=</span> <span class="k">array</span><span class="p">(),</span> <span class="nv">$leaseId</span> <span class="o">=</span> <span class="k">null</span><span class="p">,</span> <span class="nv">$additionalHeaders</span> <span class="o">=</span> <span class="k">array</span><span class="p">())</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nv">$containerName</span> <span class="o">===</span> <span class="s1">''</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Container name is not specified.'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">self</span><span class="o">::</span><span class="na">isValidContainerName</span><span class="p">(</span><span class="nv">$containerName</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Container name does not adhere to container naming conventions. See http://msdn.microsoft.com/en-us/library/dd135715.aspx for more information.'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="nv">$blobName</span> <span class="o">===</span> <span class="s1">''</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Blob name is not specified.'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="nv">$localFileName</span> <span class="o">===</span> <span class="s1">''</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Local file name is not specified.'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nb">file_exists</span><span class="p">(</span><span class="nv">$localFileName</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Local file not found.'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="nv">$containerName</span> <span class="o">===</span> <span class="s1">'$root'</span> <span class="o">&amp;&amp;</span> <span class="nb">strpos</span><span class="p">(</span><span class="nv">$blobName</span><span class="p">,</span> <span class="s1">'/'</span><span class="p">)</span> <span class="o">!==</span> <span class="k">false</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">Microsoft_WindowsAzure_Exception</span><span class="p">(</span><span class="s1">'Blobs stored in the root container can not have a name containing a forward slash (/).'</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="c1">// rest of the code here</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The rest of this components public API methods look about the same. It is a
very complete validation of the input data, however its not very readable.
Instead you have 6 if branches, which increase the complexity of the method
and almost take up half the screen without even getting to the actual code.</p>
<p>The assertion pattern is really helpful here to reduce the complexity of this
code and hide the <tt class="docutils literal"><span class="pre">if/throw</span></tt> conditions into little helper methods. Have a
look at a refactored method using my <a class="reference external" href="https://github.com/beberlei/assert">Assert</a> micro-library.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">public</span> <span class="k">function</span> <span class="nf">putBlob</span><span class="p">(</span><span class="nv">$containerName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$blobName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$localFileName</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nv">$metadata</span> <span class="o">=</span> <span class="k">array</span><span class="p">(),</span> <span class="nv">$leaseId</span> <span class="o">=</span> <span class="k">null</span><span class="p">,</span> <span class="nv">$additionalHeaders</span> <span class="o">=</span> <span class="k">array</span><span class="p">())</span>
<span class="p">{</span>
    <span class="nx">Assertion</span><span class="o">::</span><span class="na">notEmpty</span><span class="p">(</span><span class="nv">$containerName</span><span class="p">,</span> <span class="s1">'Container name is not specified'</span><span class="p">);</span>
    <span class="nx">self</span><span class="o">::</span><span class="na">assertValidContainerName</span><span class="p">(</span><span class="nv">$containerName</span><span class="p">);</span>
    <span class="nx">Assertion</span><span class="o">::</span><span class="na">notEmpty</span><span class="p">(</span><span class="nv">$blobName</span><span class="p">,</span> <span class="s1">'Blob name is not specified.'</span><span class="p">);</span>
    <span class="nx">Assertion</span><span class="o">::</span><span class="na">notEmpty</span><span class="p">(</span><span class="nv">$localFileName</span><span class="p">,</span> <span class="s1">'Local file name is not specified.'</span><span class="p">);</span>
    <span class="nx">Assertion</span><span class="o">::</span><span class="na">file</span><span class="p">(</span><span class="nv">$localFileName</span><span class="p">,</span> <span class="s1">'Local file name is not specified.'</span><span class="p">);</span>
    <span class="nx">self</span><span class="o">::</span><span class="na">assertValidRootContainerBlobName</span><span class="p">(</span><span class="nv">$containerName</span><span class="p">,</span> <span class="nv">$blobName</span><span class="p">);</span>

    <span class="c1">// rest of the code</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This is much more readable, using two custom assertions and some general
assertions.</p>
<p>There is one risk here though, you introduce additional coupling to another
library/namespace. Especially when you start using this pattern on a large
scale, you have to make sure this assertions are <strong>VERY</strong> stable and
unit-tested.</p>
<p>That is why you should extend from <tt class="docutils literal"><span class="pre">Assertion</span></tt> and use your own class when
using the Assert library. This returns some control in your hands and even
allows you to overwrite the exception class:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">namespace</span> <span class="nx">MyProject\Util</span><span class="p">;</span>

<span class="k">use</span> <span class="nx">Assert\Assertion</span> <span class="k">as</span> <span class="nx">BaseAssertion</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">Assertion</span> <span class="k">extends</span> <span class="nx">BaseAssertion</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="k">protected</span> <span class="nv">$exceptionClass</span> <span class="o">=</span> <span class="s1">'MyProject\Util\AssertionFailedException'</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Tue, 04 Sep 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/26/symfony__monolog_and_different_log_types.html</link>
            <guid>http://www.whitewashing.de/2012/08/26/symfony__monolog_and_different_log_types.html</guid>
            <title><![CDATA[Symfony, Monolog and different log types]]></title>
            <description><![CDATA[<div class="section" id="symfony-monolog-and-different-log-types">
<h1>Symfony, Monolog and different log types</h1>
<p>Symfony uses the excellent Monolog library for logging everything related
to the symfony application stack. But sometimes you need a different logger
that responds differently to the log error levels. Ideally you don’t want
to reuse the application log mechanism to avoid messing with the
fingers crossed listener of Monolog, that keeps the application log files small
in case no errors occur.</p>
<p>This can be easily done with Symfonys MonologBundle with a feature called
channel. Every log handler, such as file, syslog, mail or
fingers crossed is attached to the default logger called “app”. This is
referenced by the dependency injection service called <tt class="docutils literal"><span class="pre">monolog.logger</span></tt>.</p>
<p>If you want to create a different logger service that is responsible for a
different type of your application stack, just define it using the <tt class="docutils literal"><span class="pre">channels</span></tt>
option:</p>
<div class="highlight-yaml"><pre>monolog:
    handlers:
        myfile:
            type: stream
            path: %kernel.logs_dir%/myfile.log
            channels: mychannel</pre>
</div>
<p>To actually write to <tt class="docutils literal"><span class="pre">mychannel</span></tt> you have to tag all the services that use
<tt class="docutils literal"><span class="pre">mychannel</span></tt> with the following tag:</p>
<div class="highlight-xml"><div class="highlight"><pre><span class="nt">&lt;service</span> <span class="na">id=</span><span class="s">&quot;my_service&quot;</span> <span class="na">class=</span><span class="s">&quot;MyService&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;tag</span> <span class="na">name=</span><span class="s">&quot;monolog.logger&quot;</span> <span class="na">channel=</span><span class="s">&quot;mychannel&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;argument</span> <span class="na">type=</span><span class="s">&quot;service&quot;</span> <span class="na">id=</span><span class="s">&quot;logger&quot;</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/service&gt;</span>
</pre></div>
</div>
<p>With this approach you are now as flexible as with the default channel <tt class="docutils literal"><span class="pre">app</span></tt>
regarding to logging in development, testing and production environments for
example. Once there is a channel created through the DIC tag, you can actually
fetch it from the DIC with <tt class="docutils literal"><span class="pre">monolog.logger.mychannel</span></tt> in our example.
I don’t like this approach too much, because it misuses tags for modifying
arguments, where tags are actually for the services themselves. However it is
usable and works.</p>
<p>This feature is included starting with Symfony 2.1. It is <a class="reference external" href="http://symfony.com/doc/master/cookbook/logging/channels_handlers.html">documented in a
cookbook entry</a>,
however some insights of this blog post are still inside a pending Pull
Request.</p>
</div>]]></description>
            <pubDate>Sun, 26 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/26/froscon_2012.html</link>
            <guid>http://www.whitewashing.de/2012/08/26/froscon_2012.html</guid>
            <title><![CDATA[FrOSCon 2012]]></title>
            <description><![CDATA[<div class="section" id="froscon-2012">
<h1>FrOSCon 2012</h1>
<p>This years <a class="reference external" href="http://www.froscon.org">Free and Open Source Conference (FrOSCon)</a> took place this weekend in Bonn, St.  Augustin.
Because I live in Bonn, visiting the conference is a given for very many years
now. This year I also did a talk on “Architecture Design Patterns” with <a class="reference external" href="http://twitter.com/go_oh">Gordon</a> so there was an incentive to show up besides
meeting friends, all the Club Mate and <a class="reference external" href="http://www.quijote-kaffee.de">good open source coffee</a>.</p>
<p>The most interesting topic in this years conference for me has been the <a class="reference external" href="http://graylog2.org/">Graylog2</a> talk by Lennart Koopmann. Graylog is a logging server
that uses Elastic Search for persistence and searching. It is sponsored by
Xing, a pretty big german based Linkedin clone.</p>
<p>The talk <a class="reference external" href="http://programm.froscon.de/2012/events/954.html">The State of PHPUnit</a> by <a class="reference external" href="http://twitter.com/__edorian/">Volker</a> was interesting to see all the new stuff in
PHPUnit 3.7 and that it fixes a bunch of annoyances that I stumbled on myself.
I actually realized that they are so deeply rooted in my brain already, that
they constitute features for me, not something that could actually be
optimized. Well done to Volker and Sebastian to the new version.</p>
<p>Igors talk about building an HTTP server in PHP was interesting to see the
stream/socket server APIs of PHP at work. Ever since I took part in <a class="reference external" href="https://github.com/conradmueller/maexchen">the
SoCraTes 2012 Conference Maexchen UDP Bot</a> challenge I think network
programming is an interesting topic for learning about languages and
programming itself.</p>
<p>Volker did a second talk on sunday about Clean Code that was both entertaining
and interesting. He was reminding the audience that shipping the code is what
actually creates the value in our profession. Hence clean code is not about
the beauty of code itself, but its ability to be shippable, changeable and
adaptable to the business.</p>
<p>Again FrOSCon 2012 was awesome. Thank you very much especially to all the
volunteers that organized this event. It really good event to bring together
people from many different open-source communities and I already look forward
to the next FrOSCon 2013.</p>
</div>]]></description>
            <pubDate>Sun, 26 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/25/decoupling_applications_with_domain_events.html</link>
            <guid>http://www.whitewashing.de/2012/08/25/decoupling_applications_with_domain_events.html</guid>
            <title><![CDATA[Decoupling applications with Domains Events]]></title>
            <description><![CDATA[<div class="section" id="decoupling-applications-with-domains-events">
<h1>Decoupling applications with Domains Events</h1>
<p>In the <a class="reference external" href="http://whitewashing.de/2012/08/18/oop_business_applications__command_query_responsibility_seggregation.html">previous posts</a>
I have described 3 architectural patterns for business applications. Applying
them to your software helps you decouple the business logic from the
application/framework/UI. However given sufficient complexity, you will want to
decouple different parts of your business model from each other as well.</p>
<p>As an example, lets think of a batch process in your application that updates
orders from a CRM or logistics system:</p>
<ul class="simple">
<li>You receive an XML with full users and order representations</li>
<li>You need to update certain user fields</li>
<li>You need to update certain order fields</li>
<li>Some orders require creating accounts in different remote systems</li>
<li>If the user has not confirmed his email yet he should receive an opt-in
mail instead.</li>
<li>If the user confirms his opt-in mail, all outstanding remote accounts are
created.</li>
</ul>
<p>You can build all the steps into a single batch processing service. This will
be a particularly huge service and in violation of the <a class="reference external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility
principle</a>.</p>
<p>the part with updating of users and fields has nothing to with the sending of
mails and creation of remote accounts.  We want to decouple them from each
other.</p>
<p>The first obvious choice is to decouple them into distinct services:</p>
<ul class="simple">
<li>Import Service</li>
<li>Authentication Service</li>
<li>Account Generation Service</li>
</ul>
<p>All these services have dependencies on infrastructure objects, database,
mailer and so on. We could inject the authentication and account generation
services into the Import Service, but with rising complexity this will lead to
a lasagna of services and the execution path will dig deep into this and this
is not nearly as tasty as eating real lasagna.</p>
<div class="highlight-python"><pre>ImportService
|_AuthenticationService
| |_Mailer
| |_Database
|_AccountGenerationService
| |_Database
| \_RemoteFacade
\_Database</pre>
</div>
<p>This becomes more complicated when transaction semantics need to be taken care
of. For example dependencies between mailer and database services. Also you
have to take into account that the code in entities and value objects
participating in this use-case.</p>
<p>What we want instead is a sequential execution of those nested services, but
only if the parent service executed successfully:</p>
<div class="highlight-python"><pre>ImportService
\_Database

AuthenticationService
|_Mailer
\_Database

AccountGenerationService
|_Database
\_RemoteFacade</pre>
</div>
<p>We could use an event dispatcher in all of the services to notify each other,
but the <a class="reference external" href="http://martinfowler.com/eaaDev/DomainEvent.html">DomainEvent pattern</a> does this more in a much
cleaner way:</p>
<p>Every entity is an event provider and can emit events. Whenever a transaction
is committed and an hence an operation is completed successfully, we take all
the events emitted from all entities (looking at the identity map for example)
and trigger observing event handlers. However if the operation fails, we do not
trigger these event handlers.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">class</span> <span class="nc">Order</span> <span class="k">implements</span> <span class="nx">EventProviderInterface</span>
<span class="p">{</span>
    <span class="k">use</span> <span class="nx">EventProvider</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">importData</span><span class="p">(</span><span class="k">array</span> <span class="nv">$data</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// 1. do something with $data</span>

        <span class="c1">// 2. raise event</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">raise</span><span class="p">(</span><span class="k">new</span> <span class="nx">OrderImportCompleted</span><span class="p">(</span><span class="k">array</span><span class="p">(</span>
            <span class="s2">&quot;id&quot;</span> <span class="o">=&gt;</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">,</span>
            <span class="s2">&quot;data&quot;</span> <span class="o">=&gt;</span> <span class="nv">$data</span>
        <span class="p">)));</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">interface</span> <span class="nx">EventProviderInterface</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">dequeueEmittedEvents</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The Event provider trait aggregates all the events, and offers
and API for external services to pull them from the entity:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nx">trait</span> <span class="nx">EventProvider</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$emittedEvents</span> <span class="o">=</span> <span class="k">array</span><span class="p">();</span>

    <span class="k">protected</span> <span class="k">function</span> <span class="nf">raise</span><span class="p">(</span><span class="nx">DomainEvent</span> <span class="nx">Event</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$event</span><span class="o">-&gt;</span><span class="na">getMessageHeader</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">setEntity</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">emittedEvents</span><span class="p">[]</span> <span class="o">=</span> <span class="nv">$event</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">dequeueEmittedEvents</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$events</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">emittedEvents</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">emittedEvents</span> <span class="o">=</span> <span class="k">array</span><span class="p">();</span>
        <span class="k">return</span> <span class="nv">$events</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Our infrastructure must then trigger event handlers, based
on the event names. It will use <tt class="docutils literal"><span class="pre">dequeueEmittedEvents</span></tt> and making
sure the events are not emitted multiple times.</p>
<p>For reasons described below, we want the following command/event chain to happen in our system:</p>
<ul class="simple">
<li>Command executes</li>
<li>Entities emit events</li>
<li>Command transaction succeeds</li>
<li>Events trigger event handlers</li>
<li>Event handlers execute more commands</li>
<li>Restart from 1.</li>
</ul>
<p>With this approach we can decouple all services from each other and avoid
deep nesting in each other. Yet we still have transactional dependencies,
by dropping all events when the parent command fails. Transactions over
multiple commands will not have ACID properties though, instead you will have
to look into <a class="reference external" href="http://queue.acm.org/detail.cfm?id=1394128">BASE transactions</a>
that are important in systems with eventual consistency. This is one downside
that you need to take into account.</p>
<p>The Domain Event pattern is a prerequisite for full blown <a class="reference external" href="http://queue.acm.org/detail.cfm?id=1394128">CQRS</a>. My <a class="reference external" href="https://github.com/beberlei/litecqrs-php">LiteCQRS</a> library includes a simple
implementation of DomainEvent and EventProvider classes and integration into
Symfony and Doctrine ORM. Generally this pattern is very easy to implement
though, so that you can just have a look at the implementation and take the
best parts for your own.</p>
</div>]]></description>
            <pubDate>Sat, 25 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/22/building_an_object_model__no_setters_allowed.html</link>
            <guid>http://www.whitewashing.de/2012/08/22/building_an_object_model__no_setters_allowed.html</guid>
            <title><![CDATA[Building an Object Model: No setters allowed]]></title>
            <description><![CDATA[<div class="section" id="building-an-object-model-no-setters-allowed">
<h1>Building an Object Model: No setters allowed</h1>
<p>If you are using an object relational mapper or any other database
abstraction technology that converts rows to objects, then you will probably
use getter/setter methods or properties (C#) to encapsulate object properties.</p>
<p>Take <a class="reference external" href="https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Model/User.php">a look</a>
at the default <tt class="docutils literal"><span class="pre">User</span></tt> entity from the Symfony2 FOSUserBundle plugin for
example: A colossus of getter/setter methods with nearly no real business
logic. This is how most of our persistence related objects look like in PHP.
A Rails ActiveRecord such as <a class="reference external" href="https://github.com/redmine/redmine/blob/master/app/models/issue.rb">Redmines “Issue”</a> avoids
the explicit getter/setters, however generates accessors magically for you.
Nevertheless you have to add considerable amount of code to configure all the
properties. And code using these active records becomes ambiguous as well.</p>
<p>Why do we use getters/setters so much?</p>
<ul class="simple">
<li>Tools generate objects from a database, adding getters and setters
automatically.</li>
<li>Frameworks make them automatically available for database records/rows.</li>
<li>IDEs can magically create getter/setter pairs for fields.</li>
<li>We want the flexibility to change every field whenever we want.</li>
<li>It became natural in OOP to have write access to every field.</li>
</ul>
<p>However Getters/setters <a class="reference external" href="http://en.wikipedia.org/wiki/Open/closed_principle">violate the open/closed principle</a>, prevent information
hiding and <a class="reference external" href="http://stackoverflow.com/questions/565095/are-getters-and-setters-evil">should be considered evil</a>
(<a class="reference external" href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html">Long version</a>). Using
getters and setters allows to <em>decouples</em> the business logic for setting values from the
actual storage. Something that object-orientation was suppose to avoid.</p>
<div class="section" id="getting-rid-of-setters">
<h2>Getting rid of setters</h2>
<p>Avoiding setters is much simpler than getters, so lets start with them.</p>
<p>One way to avoid writing setters is a task based approach to the model. Think
of every task that is performed in an application and add a method that
changes all the affected fields at once, to perform this task. In the famous
blog example the <tt class="docutils literal"><span class="pre">Post</span></tt> object may look like:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Post</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">compose</span><span class="p">(</span><span class="nv">$headline</span><span class="p">,</span> <span class="nv">$text</span><span class="p">,</span> <span class="k">array</span> <span class="nv">$tags</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// check invariants, business logic, filters</span>

        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">headline</span> <span class="o">=</span> <span class="nv">$headline</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">text</span>     <span class="o">=</span> <span class="nv">$text</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">tags</span>     <span class="o">=</span> <span class="nv">$tags</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">publish</span><span class="p">(</span><span class="nx">\DateTime</span> <span class="nv">$onDate</span> <span class="o">=</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// check invariants, business logic, filters</span>

        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">state</span>       <span class="o">=</span> <span class="s2">&quot;published&quot;</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">publishDate</span> <span class="o">=</span> <span class="nv">$onDate</span> <span class="o">?:</span> <span class="k">new</span> <span class="nx">\DateTime</span><span class="p">(</span><span class="s2">&quot;now&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Post</span></tt> class is now much more protected from the outside and
is actually much better to read and understand. You can clearly see
the behaviors that exist on this object. In the future you might even
be able to change the state of this object without breaking client code.</p>
<p>You could even call this code domain driven, but actually its just applying
the SOLID principles to entities.</p>
</div>
<div class="section" id="tackling-getters">
<h2>Tackling getters</h2>
<p>Avoiding getters is a bit more cumbersome and given no setters, maybe
not worth the trouble anymore.</p>
<p>You still need getters to access the object state, either if you display
models directly in the view or for testing purposes. There is another way
to get rid of all the getters that you don’t need explicitly in a domain
model, using the visitor pattern in combination with view models:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">Post</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">render</span><span class="p">(</span><span class="nx">PostView</span> <span class="nv">$view</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$view</span><span class="o">-&gt;</span><span class="na">id</span>          <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">;</span>
        <span class="nv">$view</span><span class="o">-&gt;</span><span class="na">publishDate</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">publishDate</span><span class="p">;</span>
        <span class="nv">$view</span><span class="o">-&gt;</span><span class="na">headline</span>    <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">headline</span><span class="p">;</span>
        <span class="nv">$view</span><span class="o">-&gt;</span><span class="na">text</span>        <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">text</span><span class="p">;</span>
        <span class="nv">$view</span><span class="o">-&gt;</span><span class="na">author</span>      <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">author</span><span class="o">-&gt;</span><span class="na">render</span><span class="p">(</span><span class="k">new</span> <span class="nx">AuthorView</span><span class="p">);</span>

        <span class="k">return</span> <span class="nv">$view</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">PostView</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$id</span><span class="p">;</span>
    <span class="c1">//... more public properties</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There are drawbacks with this approach though:</p>
<ul class="simple">
<li>Why use the Post model in memory, when you are only passing <tt class="docutils literal"><span class="pre">PostView</span></tt>
instances to the controllers and views only anyways? Its much more efficient
to have the database map to the view objects directly. This is what CQRS
postulates as separation of read- and write model.</li>
<li>You have to write additional classes for every entity (Data transfer objects)
instead of passing the entities directly to the view. But if you want to
cleanly separate the model from the application/framework, you don’t get
around view model/data transfer objects anyways.</li>
<li>It looks awkward in tests at first, but you can write some custom assertions
to get your sanity back for this task.</li>
</ul>
</div>
<div class="section" id="what-about-the-automagic-form-mapping">
<h2>What about the automagic form mapping?</h2>
<p>Some form frameworks like the <a class="reference external" href="http://www.symfony.com">Symfony2</a> or <a class="reference external" href="http://framework.zend.com">Zend
Framework 2</a> ones map forms directly to objects
and back. Without getters/setters this is obviously not possible anymore.
However if you are decoupling the model from the framework, then using this
kind of form framework on entities is a huge no go anyways.</p>
<p>Think back to the tasks we are performing on our <tt class="docutils literal"><span class="pre">Post</span></tt> entity:</p>
<ul class="simple">
<li>Edit (title, body, tags)</li>
<li>Publish (publishDate)</li>
</ul>
<p>Both tasks allow only a subset of the properties to be modified. For each of
these tasks we need a custom form “model”. Think of these models as command
objects:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">EditPostCommand</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$id</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$headline</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$text</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$tags</span> <span class="o">=</span> <span class="k">array</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In our application we could attach these form models to our form framework and
then pass these as commands into our “real model” through a service layer,
<a class="reference external" href="http://www.eaipatterns.com/MessageBus.html">message bus</a> or something equivalent:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">PostController</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">editAction</span><span class="p">(</span><span class="nx">Request</span> <span class="nv">$request</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$post</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">findPostViewModel</span><span class="p">(</span><span class="nv">$request</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'id'</span><span class="p">));</span>

        <span class="c1">// This could need some more automation/generic code</span>
        <span class="nv">$editPostCommand</span>           <span class="o">=</span> <span class="k">new</span> <span class="nx">EditPostCommand</span><span class="p">();</span>
        <span class="nv">$editPostCommand</span><span class="o">-&gt;</span><span class="na">id</span>       <span class="o">=</span> <span class="nv">$request</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'id'</span><span class="p">);</span>
        <span class="nv">$editPostCommand</span><span class="o">-&gt;</span><span class="na">headline</span> <span class="o">=</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">headline</span><span class="p">;</span>
        <span class="nv">$editPostCommand</span><span class="o">-&gt;</span><span class="na">text</span>     <span class="o">=</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">text</span><span class="p">;</span>
        <span class="nv">$editPostCommand</span><span class="o">-&gt;</span><span class="na">tags</span>     <span class="o">=</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">tags</span><span class="p">;</span>

        <span class="c1">// here be the form framework handling...</span>
        <span class="nv">$form</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">createForm</span><span class="p">(</span><span class="k">new</span> <span class="nx">EditPostType</span><span class="p">(),</span> <span class="nv">$editPostCommand</span><span class="p">);</span>
        <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">bind</span><span class="p">(</span><span class="nv">$request</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nv">$form</span><span class="o">-&gt;</span><span class="na">isValid</span><span class="p">())</span> <span class="p">{</span>
            <span class="c1">// invalid, show errors</span>
        <span class="p">}</span>

        <span class="c1">// here we invoke the model, finally, through the service layer</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">postService</span><span class="o">-&gt;</span><span class="na">edit</span><span class="p">(</span><span class="nv">$editPostCommand</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">PostService</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">edit</span><span class="p">(</span><span class="nx">EditPostCommand</span> <span class="nv">$command</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$post</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">postRepository</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$command</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">);</span>
        <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">compose</span><span class="p">(</span><span class="nv">$command</span><span class="o">-&gt;</span><span class="na">headline</span><span class="p">,</span> <span class="nv">$command</span><span class="o">-&gt;</span><span class="na">text</span><span class="p">,</span> <span class="nv">$command</span><span class="o">-&gt;</span><span class="na">tags</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This way we separated the business model from the application framework.</p>
</div>
<div class="section" id="a-word-about-rad">
<h2>A word about RAD</h2>
<p>Rapid-application development or rapid prototyping is a wide-spread approach in web
development. My explicit approach seems to be completely against this kind of
development and much slower as well. But I think you don’t loose much time
in the long run:</p>
<ul class="simple">
<li>Simple command objects can be code-generated or generated by IDEs
in a matter of seconds. Or you could even extend ORMs code generation
capabilities to generate these dummy objects for you. Since you don’t need
ORM mapping information for these objects or think about performance
implications in context with the ORM, you don’t need to spend much
thinking about their creation.</li>
<li>Explicit models are much simpler to unit-test and those tests run much faster
than tests through the UI that RAD prototypes need.</li>
<li>Generated Rapid prototypes can get hard to maintain quickly. That does not mean they
are unmaintainable, but they seem to favour reimplementation instead of
refactoring, something that leads to problems given the low code coverage
that these prototypes normally have.</li>
</ul>
</div>
<div class="section" id="conclusion">
<h2>Conclusion</h2>
<p>If we take a step back from all our tools suggesting to generate getter/setters
we find that there is a simple way to avoid using setters when focusing on the
tasks that objects perform. This actually makes our code much more readable and
is one building block towards clean object oriented code and domain driven design.</p>
<p>I am very interested in your opinions on this topic and my attempt to avoid them,
please leave comments when leaving this website :-)</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Wed, 22 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/18/oop_business_applications__command_query_responsibility_seggregation.html</link>
            <guid>http://www.whitewashing.de/2012/08/18/oop_business_applications__command_query_responsibility_seggregation.html</guid>
            <title><![CDATA[OOP Business Applications: Command-Query-Responsibility-Segregation (CQRS)]]></title>
            <description><![CDATA[<div class="section" id="oop-business-applications-command-query-responsibility-segregation-cqrs">
<h1>OOP Business Applications: Command-Query-Responsibility-Segregation (CQRS)</h1>
<p>Other posts in this series about OOP Business Applications:</p>
<ul class="simple">
<li><a class="reference external" href="http://whitewashing.de/2012/08/11/oop_business_applications__trying_to_escape_the_mess.html">Trying to escape the
mess</a></li>
<li><a class="reference external" href="http://whitewashing.de/2012/08/13/oop_business_applications_entity_boundary_interactor.html">Entity, Boundary, Interactor</a></li>
<li><a class="reference external" href="http://whitewashing.de/2012/08/16/oop_business_applications__data__context__interaction.html">Data, Context, Interaction</a></li>
</ul>
<p>The last pattern for designing your business logic is called
“Command-Query-Responsibility-Segregation” or short CQRS. It has its roots in
the <a class="reference external" href="http://en.wikipedia.org/wiki/Command-query_separation">“Command Query Separation”</a> principle that was
put forward by Bertrand Meyer.</p>
<p>Wikipedia has a very good summary about what this principle is about:</p>
<div class="highlight-python"><pre>Command-Query-Separation states that every method should either be a
command that performs an action, or a query that returns data to the
caller, but not both. In other words, asking a question should not change
the answer. More formally, methods should return a value only if they are
referentially transparent and hence possess no side effects.</pre>
</div>
<p>CQRS is an OOP architecture design pattern building on that imperative
principle.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There are many different variations of the CQRS pattern that
all have their place. This post describes a simple variant that does
<strong>not</strong>
use Messaging, DomainEvent or EventSourcing patterns, which are commonly mentioned
with CQRS.</p>
</div>
<p>At its heart is the separation of Read and Write methods. This can be easily
achieved by just having two different service layer classes instead of one.
This insight alone is not really helpful, its just moving methods around.
Coupled to this change however is the notion, that read and write models don’t
necessarily have to be the same:</p>
<ul class="simple">
<li>Getter/Setters: We don’t need setters in the write model, instead we use
explicit methods for each write operation. Entities are also much simpler
without bi-directional relationships that read/write models often need.
Read-only models (ViewModel) don’t need getters/setters. They could just use
public properties or even be arrays.</li>
<li>ORM Performance, Lazy Loading and Query Restrictions: In a write scenario we
mostly need queries by primary key, changing only some objects. In
read scenarios we need complex queries, joins and aggregations. A separation
prevents both from affecting each other negatively.</li>
<li>Mapping Data-Transfer objects becomes simple. Instead of sending the whole
model back and forth, for the write scenario you define use-case specific
tasks and updates. This is much simpler than generic mapping of Data Transfer
objects to complex object graphs.</li>
<li>Transforming SQL directly to a view model in a highly optimized way.
Simple concept, but it has huge implications: A pure read-only model is simple to
maintain and refactor for any performance requirements that come up.</li>
</ul>
<p>Furthermore with CQRS our write service methods are not allowed to return data
anymore (With the exceptions to the rule of course). This may increase the
complexity at first, but it has benefits for scalability and decoupling.
Following this principle allows us to turn every command from synchronous to
asynchronous processing later without much problems. Services are allowed to
throw exceptions and refuse the execution. Proper validation of input data
should happen before executing write operations though.</p>
<p>One drawback of CQRS: A naive implementation doubles the amount of classes and
services to write. But there are simple shortcuts to avoid having to write a
full blown read-model if you don’t apply CQRS religiously:</p>
<ul class="simple">
<li>Don’t use different data-stores for both models.</li>
<li>Mapping SQL to PHP arrays and stdClass objects through a simple gateway is
very simple. You can easily generalize this to a simple object that gives
efficient access to all your data.</li>
<li>Share parts of the write and read models if you don’t have to compromise
much.</li>
</ul>
<p>The important thing to take away from this separation is, that the read part of
your application is seldom the part where business value lies in. Moving this
code into a different part of your applications allows you to work with the
underlying data-source much more directly, without need for much abstractions.</p>
<p>One thing that CQRS puts forward is the concept of Commands, Command Handlers
and Command Bus and how they interact. Commands are simple objects that
contain all the data necessary to execute an operation. Each command is
processed by exactly one command handler. The Command Bus is responsible to
route a command to its appropriate command handler.</p>
<div class="section" id="example">
<h2>Example</h2>
<p>Here is the most simple implementation of the Command Bus, just holds a hash map
mapping command class names to command handlers:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">Handler</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">handle</span><span class="p">(</span><span class="nv">$command</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">CommandBus</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$handlers</span><span class="p">;</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">register</span><span class="p">(</span><span class="nv">$commandClassName</span><span class="p">,</span> <span class="nx">Handler</span> <span class="nv">$handler</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">handlers</span><span class="p">[</span><span class="nv">$commandClassName</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$handler</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">handle</span><span class="p">(</span><span class="nv">$command</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">handlers</span><span class="p">[</span><span class="nb">get_class</span><span class="p">(</span><span class="nv">$command</span><span class="p">)]</span><span class="o">-&gt;</span><span class="na">handle</span><span class="p">(</span><span class="nv">$command</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In your code you would always pass Commands to the bus. That way the command
bus is a central entry point to any write operation. With this we can rewrite the
TransferMoney service:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">TransferMoneyCommand</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$sourceId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$destinationId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$money</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">MoneyTransfer</span> <span class="k">implements</span> <span class="nx">Handler</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$accountDao</span><span class="p">;</span> <span class="c1">// ctor omitted</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">handle</span><span class="p">(</span><span class="nv">$command</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$source</span>      <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">accountDao</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$command</span><span class="o">-&gt;</span><span class="na">sourceId</span><span class="p">);</span>
        <span class="nv">$destination</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">accountDao</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$command</span><span class="o">-&gt;</span><span class="na">destinationId</span><span class="p">);</span>
        <span class="nv">$money</span>       <span class="o">=</span> <span class="k">new</span> <span class="nx">Money</span><span class="p">(</span><span class="nv">$command</span><span class="o">-&gt;</span><span class="na">amount</span><span class="p">);</span>

        <span class="nv">$source</span><span class="o">-&gt;</span><span class="na">withdraw</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
        <span class="nv">$destination</span><span class="o">-&gt;</span><span class="na">deposit</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There is also a benefit from the mental model of commands compared to the
“generic” term of model requests in EBI. Your write model gets task
oriented.</p>
<p>Routing everything through the command bus has several benefits as well:</p>
<ul class="simple">
<li>Nesting handlers that take care of transactions, logging, 2 phase commits</li>
<li>Order nested command calls sequentially instead of deep into each other.</li>
<li>Asynchronous processing with message queue become an option</li>
</ul>
<p>The command bus acts as the application boundary as described in the
Entity-Boundary-Interactor pattern, usage is simple:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MoneyController</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferAction</span><span class="p">(</span><span class="nx">Request</span> <span class="nv">$request</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$commandBus</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">container</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'command_bus'</span><span class="p">);</span>
        <span class="nv">$commandBus</span><span class="o">-&gt;</span><span class="na">handle</span><span class="p">(</span><span class="k">new</span> <span class="nx">TransferMoneyCommand</span><span class="p">(</span>
            <span class="nv">$request</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'sourceId'</span><span class="p">),</span>
            <span class="nv">$request</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'destinationId'</span><span class="p">),</span>
            <span class="k">new</span> <span class="nx">Money</span><span class="p">(</span><span class="nv">$request</span><span class="o">-&gt;</span><span class="na">request</span><span class="o">-&gt;</span><span class="na">get</span><span class="p">(</span><span class="s1">'amount'</span><span class="p">)</span>
        <span class="p">));</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="pros-and-cons">
<h2>Pros and Cons</h2>
<p>I really like CQRS for multiple reasons. It offers explicit guidance how solve
tasks by making use of a range of different design patterns. This is very
helpful, because the code-base is based on conventions that are simple to
understand by everyone on the team. This structure liberates you from the curse
of choice and gives you a cookbook of best-practices how to solve problems.
You want this structure for all your applications, regardless of what
architectural pattern you have chosen.</p>
<p>Embracing the difference between read and write models is another plus of CQRS.
It is very helpful, not to try fitting both read and write into one model.  You
also don’t run into so many read-related problems with an ORM any more. You
design the entities to be optimized for the write model only, loose the
bidirectional associations and avoid all the optimizations here and there for
read performance.</p>
<p>Compared to EBI, where we had to maintain a mapping between DTOs and entities,
CQRS explicitly uses the command based approach to avoid the complexity of
these mappings. You will still have to map between command and entity, however
doing so in the context of a use-case simplifies the code considerably compared
to a generic mapping solution.</p>
<p>One negative point: Its difficult to work with commands not returning any data
in some cases. You need to find simple ways to return messages to the
user. For that you also need to validate commands on the “client” or
controller side, using the read model, so that you can prevent invalid/illegal
commands from being sent as often as possible.</p>
<p>Without return values from your models, you are left to using mocks as means of
testing. This might be more difficult for developers to use and understand.
This problem goes away however, if you combine CQRS with Event Sourcing. A
topic that I will discuss in the next blog post.</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Sat, 18 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/16/oop_business_applications__data__context__interaction.html</link>
            <guid>http://www.whitewashing.de/2012/08/16/oop_business_applications__data__context__interaction.html</guid>
            <title><![CDATA[OOP Business Applications: Data, Context, Interaction]]></title>
            <description><![CDATA[<div class="section" id="oop-business-applications-data-context-interaction">
<h1>OOP Business Applications: Data, Context, Interaction</h1>
<p>Other posts in this series:</p>
<ul class="simple">
<li><a class="reference external" href="http://whitewashing.de/2012/08/11/oop_business_applications__trying_to_escape_the_mess.html">OOP Business Applications: Trying to escape the
mess</a></li>
<li><a class="reference external" href="http://whitewashing.de/2012/08/13/oop_business_applications_entity_boundary_interactor.html">OOP Business Applications: Entity, Boundary, Interactor</a></li>
</ul>
<p>The next design pattern for technical system design is called “Data, Context,
Interaction”. It’s inventors Trygve Reenskaug and James Coplien call it a new
paradigm, in the context of PHPs language constraints it can be classified as
architectural design pattern. I came across this pattern through <a class="reference external" href="https://twitter.com/go_oh">Gordon Oheim</a>. He has also invested quite some time going
through the book on DCI and trying to understand this pattern with me.</p>
<p>As in the EBI pattern, DCI separates data objects (Data) from behavior implemented
in use-cases (Context). Data objects are never directly involved in these
use-cases, but are “casted” to their respective roles that they are taking in
the use-case. This can be implemented with aggregation or traits in PHP.</p>
<p>One goal of DCI is to get object-oriented programming to a place, where you
can look at a use-case and its roles and be very sure that the program is
running correctly, because you can guarantee that there are no unexpected side
effects. It also aims at keeping the amount of code required to keep in mind
for a given use-case as small as possible, allowing developers to reason about
the code with more confidence.</p>
<div class="section" id="terminology">
<h2>Terminology</h2>
<p>In DCI, <strong>data</strong> are objects that encapsulate the state of the application.
As in EBI, they only contain logic that is true for all the possible use-cases.
These classes represent <em>what the system is</em>.</p>
<p><strong>Roles</strong> and <strong>Context</strong> represent <em>what the system does</em> and are supposed to
capture the End User’s Mental Model as close as possible.</p>
<p><strong>Roles</strong> add behavior to the data objects by either wrapping them or
acting as traits for the data objects.</p>
<p><strong>Context</strong> is the use-case and fulfils its role by making roles <strong>interact</strong> with
each other. These roles then modify the underlying data.</p>
</div>
<div class="section" id="example">
<h2>Example</h2>
<p>Starting from the bank account example of the EBI post, we can introduce DCI
quite easily by adding the missing concept of roles. In the use case of
transferring money that would be:</p>
<ul class="simple">
<li>TransferMoneySource</li>
<li>TransferMoneySink (Destination)</li>
</ul>
<p>We can do this by either introducing two interfaces and two concrete
implementations that accept the <tt class="docutils literal"><span class="pre">BankAccount</span></tt> as object to work on
or by building two traits. I will go down the route with traits, to show
one possible use-case for this new PHP 5.4 feature. The idea here is to
implement all the behavior necessary on a trait and then have simple dummy
objects using them in the tests for this use-case.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nx">trait</span> <span class="nx">TransferMoneySource</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferTo</span><span class="p">(</span><span class="nv">$destination</span><span class="p">,</span> <span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$destination</span><span class="o">-&gt;</span><span class="na">transferFrom</span><span class="p">(</span><span class="nv">$destination</span><span class="p">,</span> <span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">abstract</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">withdraw</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">trait</span> <span class="nx">TransferMoneySink</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferFrom</span><span class="p">(</span><span class="nv">$source</span><span class="p">,</span> <span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$source</span><span class="o">-&gt;</span><span class="na">withdraw</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">deposit</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">abstract</span> <span class="k">public</span> <span class="k">function</span> <span class="nf">deposit</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Any checks for balances, credit limits or other things would also happen
here. The <tt class="docutils literal"><span class="pre">withdraw</span></tt> and <tt class="docutils literal"><span class="pre">deposit</span></tt>  on the data objects should be as
dumb as possible, so that their implementation does not cause any side-effects
on the execution of this use-case.</p>
<p>The bank account would then be modified to look:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>

<span class="k">class</span> <span class="nc">BankAccount</span>
<span class="p">{</span>
    <span class="k">use</span> <span class="nx">TransferMoneySource</span><span class="p">,</span> <span class="nx">TransferMoneySink</span><span class="p">;</span>

    <span class="k">private</span> <span class="nv">$balance</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Money</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">withdraw</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span><span class="o">-&gt;</span><span class="na">subtract</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">deposit</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The use-case <tt class="docutils literal"><span class="pre">TransferMoney</span></tt> would then be modified to create Roles instead
of Data objects from the DAO. This can be a bit tricky when you have multiple
data objects implementing the same role and you have no way of knowing which
underlying data object to pick. The binding of data objects to roles happens
in the use-case. The use-case needs a means to retrieve objects with certain
roles, which then access underlying data sources. To avoid that your use-cases
have to know about how to bind roles to data, you could use GUIDs in your
application and fetch all objects from one data store. Another way would be to
implement data access objects for roles, that then know how to retrieve their
corresponding data.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MoneyTransfer</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$source</span><span class="p">;</span>
    <span class="k">private</span> <span class="nv">$destination</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$moneySource</span><span class="p">,</span> <span class="nv">$moneySink</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">source</span> <span class="o">=</span> <span class="nv">$moneySource</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">destination</span> <span class="o">=</span> <span class="nv">$moneySink</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferMoney</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">source</span><span class="o">-&gt;</span><span class="na">transferTo</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">destination</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The simplicity of this is appealing, however don’t forget that we have
abstracted I/O completely here. There has to be code that deals with that part
of the system somewhere. However this again is not at the heart of all the DCI
examples out there, making it difficult to reason about the actual practical
implications.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">One drawback with this example is, that PHP does not support typehinting for
traits.</p>
</div>
<p>Here is an example of how the bank application service could look like:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">BankApplicationService</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferMoney</span><span class="p">(</span><span class="nv">$sourceId</span><span class="p">,</span> <span class="nv">$destinationId</span><span class="p">,</span> <span class="nx">Money</span> <span class="nv">$amount</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$source</span>      <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">objectStorage</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$sourceId</span><span class="p">);</span>
        <span class="nv">$destination</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">objectStorage</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$destinationId</span><span class="p">);</span>

        <span class="nv">$useCase</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MoneyTransfer</span><span class="p">(</span><span class="nv">$source</span><span class="p">,</span> <span class="nv">$destination</span><span class="p">);</span>

        <span class="nv">$conn</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">conn</span><span class="o">-&gt;</span><span class="na">beginTransaction</span><span class="p">();</span>

        <span class="k">try</span> <span class="p">{</span>
            <span class="nv">$result</span> <span class="o">=</span> <span class="nv">$useCase</span><span class="o">-&gt;</span><span class="na">transferMoney</span><span class="p">(</span><span class="nv">$amount</span><span class="p">);</span>
            <span class="nv">$conn</span><span class="o">-&gt;</span><span class="na">commit</span><span class="p">();</span>

            <span class="k">return</span> <span class="nv">$result</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">catch</span><span class="p">(</span><span class="nx">\Exception</span> <span class="nv">$e</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$conn</span><span class="o">-&gt;</span><span class="na">rollback</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">ObjectStorage</span></tt> here is a service (repository) that can find any
persistent data object by a global ID. This is necessary, because it
doesn’t actually matter what data object uses the necessary traits
for this use-case.</p>
<p>Again as in EBI, in a bigger system you would need to find some abstraction
layer that does this in a more generic way.</p>
</div>
<div class="section" id="conclusion">
<h2>Conclusion</h2>
<p>When Gordon started showing me this pattern we were both puzzled as how
to actually implement this in the real world. Especially the concept
of binding roles to data objects still confuses us. Most notably why the use
of traits or aggregates should actually constitute a new programming paradigm
instead of just another way to do OOP.</p>
<p>In Scala casting data objects to roles is actually possible by binding traits
to objects at runtime. This is not possible in PHP however and has to be done
statically.</p>
<p>Compared to EBI, DCI focuses drastically on transaction script domain logic, by
suggesting to implement roles for every use-case for the sake of avoiding
side-effects. This is actually is very valuable lesson from this pattern.
Finding means to decrease the complexity of software is always a good thing.
And the explicit definition of this concept as <strong>roles</strong> is actually easy to
explain to other programmers.</p>
<p>One thing that is lacking in DCI is that there is no concrete mechanism to deal
with the boundary to other parts of the system. This is actually a step back
from EBI and I suggest using EBI pattern in combination with DCI to solve this.</p>
<p>The largest benefit from DCI (and its self proclaimed goal) is the mapping from
the users/customers mental model directly into the code by using Use-Cases and
Roles. The communication with the customer about behavior can exclusively focus
on the current context and its use-case. Mapping this behavior to actual data
can then be done in a different step.</p>
<p>This simplification of use-cases and reduction of side-effects between
different parts of the system has other benefits: It can lead to easier to test
code and makes it much easier for developers to develop on small and isolated
parts of the system.</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Thu, 16 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/13/oop_business_applications_entity_boundary_interactor.html</link>
            <guid>http://www.whitewashing.de/2012/08/13/oop_business_applications_entity_boundary_interactor.html</guid>
            <title><![CDATA[OOP Business Applications: Entity, Boundary, Interactor]]></title>
            <description><![CDATA[<div class="section" id="oop-business-applications-entity-boundary-interactor">
<h1>OOP Business Applications: Entity, Boundary, Interactor</h1>
<p>Other posts in this series:</p>
<ul class="simple">
<li><a class="reference external" href="http://whitewashing.de/2012/08/11/oop_business_applications__trying_to_escape_the_mess.html">OOP Business Applications: Trying to escape the
mess</a></li>
</ul>
<p>Continuing the series, I will talk about Entity, Boundary and Interactor (EBI)
an architectural design pattern. I first heard about it in a keynote video of
<a class="reference external" href="https://sites.google.com/site/unclebobconsultingllc/">Uncle Bob</a> on Ruby
Midwest called <a class="reference external" href="http://www.confreaks.com/videos/759-rubymidwest2011-keynote-architecture-the-lost-years">“The lost years of architecture”</a>.
This is also described as <a class="reference external" href="http://alistair.cockburn.us/Hexagonal+architecture">Hexagonal architecture</a> or “Ports and Adapters”
by Alistair Cockburn.</p>
<p>In this pattern any client of the system talks to the model using a model
request object and receives data from the model in form of model responses objects.
Additionally when your model talks to any kind of persistence or subsystem it
should go through an adapter that is replaceable. For a model architecture
designed this way, you can replace any part of the UI oder lower layers by
writing new adapters and plug them in.</p>
<div class="section" id="terminology">
<h2>Terminology</h2>
<p>To iterate the terminology:</p>
<p><strong>Entities</strong> are objects that represent the system data of the application. They don’t contain
much logic except rules that are set in stone and are never going to change
(based on physic or mathematical laws or something).</p>
<p><strong>Interactors</strong> are use-case objects, they contain the business logic that is valid
in the current use-case and works with entities to fulfil their task.</p>
<p>The <strong>boundary</strong> is responsible for translating model request/response into a
format that the UI or actor can understand. They also mediate between model
and lower levels, for example to manage database transactions.</p>
</div>
<div class="section" id="an-example">
<h2>An example</h2>
<p>Lets start with an example in PHP code. We will keep using a common example
throughout all blog posts, the usual Bank Account/Money Transfer. The use case
is the money transfer from one bank account (source) to another one
(destination).</p>
<p>We start by implementing the entity <tt class="docutils literal"><span class="pre">BankAccount</span></tt>:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">BankAccount</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$balance</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Money</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">withdraw</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span><span class="o">-&gt;</span><span class="na">subtract</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">deposit</span><span class="p">(</span><span class="nx">Money</span> <span class="nv">$money</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">balance</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>It is straightforward to implement the <tt class="docutils literal"><span class="pre">withdraw</span></tt> and <tt class="docutils literal"><span class="pre">deposit</span></tt>
functionality. The Money object implementation is omitted here.</p>
<p>The Interactor handles the use-case of transferring money from the
source to the destination account:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MoneyTransferRequest</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="nv">$sourceId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$destinationId</span><span class="p">;</span>
    <span class="k">public</span> <span class="nv">$amount</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">MoneyTransferResponse</span>
<span class="p">{</span>
<span class="p">}</span>

<span class="k">class</span> <span class="nc">MoneyTransfer</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$accountDao</span><span class="p">;</span> <span class="c1">// ctor omitted</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferMoney</span><span class="p">(</span><span class="nx">MoneyTransferRequest</span> <span class="nv">$transfer</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$source</span>      <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">accountDao</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$transfer</span><span class="o">-&gt;</span><span class="na">sourceId</span><span class="p">);</span>
        <span class="nv">$destination</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">accountDao</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$transfer</span><span class="o">-&gt;</span><span class="na">destinationId</span><span class="p">);</span>
        <span class="nv">$money</span>       <span class="o">=</span> <span class="k">new</span> <span class="nx">Money</span><span class="p">(</span><span class="nv">$transfer</span><span class="o">-&gt;</span><span class="na">amount</span><span class="p">);</span>

        <span class="nv">$source</span><span class="o">-&gt;</span><span class="na">withdraw</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>
        <span class="nv">$destination</span><span class="o">-&gt;</span><span class="na">deposit</span><span class="p">(</span><span class="nv">$money</span><span class="p">);</span>

        <span class="k">return</span> <span class="k">new</span> <span class="nx">MoneyTransferResponse</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">MoneyTransferRequest</span></tt> and <tt class="docutils literal"><span class="pre">MoneyTransferResponse</span></tt> objects are dumb
php objects (so called data-transfer objects, DTO).</p>
<p>You can see in the example that we use a Data Access object to retrieve the
source and destination account entities from some storage subsystem. To follow the EBI
design pattern, we have to decouple this data access object from the model,
by offering a port (Interface):</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">interface</span> <span class="nx">AccountDaoInterface</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">find</span><span class="p">(</span><span class="nv">$accountId</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This way our business logic is storage independent.</p>
<p>An example for a boundary would be the requirement for a transaction in
the bank account sample. We need to wrap the whole MoneyTransfer use-case in
a transaction. Lets say the invocation of our Use-Case is controlled through
some kind of application boundary object:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">BankApplicationBoundary</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$applicationFactory</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">transferMoney</span><span class="p">(</span><span class="nx">MoneyTransferRequest</span> <span class="nv">$request</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$connection</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">applicationFactory</span><span class="o">-&gt;</span><span class="na">createConnection</span><span class="p">();</span>
        <span class="nv">$connection</span><span class="o">-&gt;</span><span class="na">beginTransaction</span><span class="p">();</span>

        <span class="k">try</span> <span class="p">{</span>
            <span class="nv">$useCase</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MoneyTransfer</span><span class="p">(</span><span class="nv">$factory</span><span class="o">-&gt;</span><span class="na">createAccountDao</span><span class="p">());</span>
            <span class="nv">$result</span> <span class="o">=</span> <span class="nv">$useCase</span><span class="o">-&gt;</span><span class="na">transferMoney</span><span class="p">(</span><span class="nv">$request</span><span class="p">);</span>
            <span class="nv">$connection</span><span class="o">-&gt;</span><span class="na">commit</span><span class="p">();</span>

            <span class="k">return</span> <span class="nv">$result</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">catch</span><span class="p">(</span><span class="nx">\Exception</span> <span class="nv">$e</span><span class="p">)</span> <span class="p">{</span>
            <span class="nv">$connection</span><span class="o">-&gt;</span><span class="na">rollback</span><span class="p">();</span>
            <span class="k">throw</span> <span class="nv">$e</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This is a very elaborate way to describe that calling the transfer money
use-case is wrapped in a Transaction, another port for the storage system to
manage transactions in this case. The code here is very explicit about
the actual task. In a real application you would probably find a more
generic approach to getting this job done.</p>
</div>
<div class="section" id="boundary-abstraction">
<h2>Boundary Abstraction</h2>
<p>Thinking about the boundaries I came up with a library several month ago called
<a class="reference external" href="https://github.com/beberlei/context">Context</a>, which I deprecated already
(Reason below).  It allows you to wrap calls to the model by some sort of proxy
that transforms the request and response and also handles transactions and
such. Loosely spoken this was actually some kind of AOP library, using the
limited ways that PHP provides to implement AOP (magic <tt class="docutils literal"><span class="pre">__call</span></tt> proxies).</p>
<p>With context you would do something like:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nv">$context</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getContext</span><span class="p">();</span>

<span class="c1">// 1. direct invocation</span>
<span class="nv">$myService</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MyService</span><span class="p">();</span>
<span class="nv">$context</span><span class="o">-&gt;</span><span class="na">execute</span><span class="p">(</span><span class="k">array</span><span class="p">(</span><span class="s1">'service'</span> <span class="o">=&gt;</span> <span class="nv">$myService</span><span class="p">,</span> <span class="s1">'method'</span> <span class="o">=&gt;</span> <span class="s1">'doSomething'</span><span class="p">,</span> <span class="s1">'arguments'</span> <span class="o">=&gt;</span> <span class="nv">$args</span><span class="p">));</span>

<span class="c1">// 2. proxy wrapping</span>
<span class="nv">$myService</span> <span class="o">=</span> <span class="nv">$context</span><span class="o">-&gt;</span><span class="na">wrap</span><span class="p">(</span><span class="k">new</span> <span class="nx">MyService</span><span class="p">());</span>
<span class="nv">$myService</span><span class="o">-&gt;</span><span class="na">doSomething</span><span class="p">(</span><span class="nv">$args</span><span class="p">);</span>
</pre></div>
</div>
<p>The second way is obviously way more readable, but its also rather magic.</p>
<p>I deprecated this library because in the end it wasn’t really helpful that
much. Implementing an application specific proxy for services is done in
almost no time and then it solves all your specific needs. My main problem with
the library is that it tries to magically take away the need to design the
boundary of your application yourself - in a way that is not really coherent to
other developers.</p>
<p>In my own current greenfield applications I quickly went away from using it,
since a custom application proxy as shown in this
<a class="reference external" href="https://gist.github.com/3272909">Gist</a> is really much simpler to implement and
use.</p>
</div>
<div class="section" id="using-with-symfony2">
<h2>Using with Symfony2</h2>
<p>As I am currently exclusively developing Symfony2/Silex applications, applying
EBI to Symfony2 framework based applications is very important to me. The
biggest difficulty here is the Form layer, especially the request data-mapping and
validation concerns, which are normally part of the model. There are two
approaches I came up with to solve this:</p>
<ul class="simple">
<li>Build Forms for arrays or DTOs and send them through to the boundary to the model.
You have to validate the data again on the model, which is annoying, but in
this case the clean way. This is not so easy to do with complex forms though
as you need to map the request objects to your entities.</li>
<li>Create a Model Request that wraps and hides the form behind a simple data
mapping API. This way you can make it look as if you would map a DTO onto
an object, but in this case you are using the Form API as the mapper.</li>
</ul>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">class</span> <span class="nc">MyService</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">edit</span><span class="p">(</span><span class="nx">EditRequest</span> <span class="nv">$request</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$entity</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dao</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$request</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">dataMapper</span><span class="o">-&gt;</span><span class="na">transform</span><span class="p">(</span><span class="nv">$request</span><span class="p">,</span> <span class="nv">$data</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The problem with this approach is, that you cant really unit-test these methods
anymore, because the complexity of the form layer mapping cannot be mocked with
this API. Instead your tests always need the full form layer (with validation,
depending services etc.) to allow for real-world testing. Additionally you have
to make the DataMapper throw an exception that you can catch in the controller,
rendering the appropriate response. Using exceptions for controlling executions
paths is not a very good practice though.</p>
<p>Another thing that actually helped was the SensioFrameworkExtraBundle and
ParamConverters. In my project I now have the framework building the Model
Request objects by convention from the HTTP Request, so that I only need to
pass them on and can skip the actual mapping of HTTP Request to Model Request.</p>
</div>
<div class="section" id="pros-and-cons">
<h2>Pros and Cons</h2>
<p>This design pattern very closely resembles what Fowler calls <strong>Service Layer</strong>
pattern in PoEAA. EBI is going a bit more into detail by naming individual
parts of the pattern more explicit. Without more restrictions however using
this pattern will drive you towards many of the problems described in my
previous post.</p>
<p>Clean separation from frameworks is achieved, depending on the actual usage
however only at a significant cost.  Never forget stepping back and thinking
about further abstractions, otherwise applying EBI is leading to lots of code
being manually written.</p>
<p>This already shows one particular annoyance are the data-transfer objects. You
need to invest quite some work to get a mapping working from entities to
transfer objects and back. In the process you will loose the convenience of
“Open Entity Manager in the View”, where you can lazy load any
data you want to access in the view. This is quite a painful step, because you
are loosing lots of flexibility. Much more annoying is the need to update
entities from data-transfer objects, requiring sophisticated code for merging
of partial object graphs.</p>
<p>What this design pattern improves is the testability of code and also the
execution of tests is MUCH better, when you don’t have to go through the whole
application stack to test something.</p>
<p>Implementing behavior into the use-cases also avoids lots of lasagna code
compared to a messy domain driven design. You get a very good overview of
what is actually happening just by looking at the Model Request and Interactor
classes. However depending on the use-case the classes can get very big
and might need lots of collaborators, which make the problem complex again.</p>
<p>It is important to note that aggregating the domain logic in the use-cases
actually means going to some sort of transaction script processing, away from
domain driven design. I am pretty sure that this is not necessarily the
intention of this design pattern from a POV of Uncle Bob. However depending on
the sophistication of the applications domain logic, transaction script is
actually a very good pattern for simple to medium complex use-cases and
I like to have this as a general rule for developers (“Put behavior on the
use-case”).</p>
<p>In conclusion I can partially recommend using the EBI pattern. You have to be
careful to find abstraction layers that keep your code DRY and SOLID however,
something which does not come naturally with this pattern. If you are not
careful you end up with all the “messy points” that I mentioned in my previous
blog post.</p>
<p>You should be especially careful to avoid lots of DTO &lt;-&gt; Entity Mapping code
by using some code-generation for example to do parts of this job for you. The
worst outcome with this pattern is, when you manually code layers for HTTP
Request/Form =&gt; DTO =&gt; Entity mapping and the other way around.</p>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Mon, 13 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/08/11/oop_business_applications__trying_to_escape_the_mess.html</link>
            <guid>http://www.whitewashing.de/2012/08/11/oop_business_applications__trying_to_escape_the_mess.html</guid>
            <title><![CDATA[OOP Business Applications: Trying to escape the mess]]></title>
            <description><![CDATA[<div class="section" id="oop-business-applications-trying-to-escape-the-mess">
<h1>OOP Business Applications: Trying to escape the mess</h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">tl;dr Version: I present a list of problems with OOP business applications from
my personal experience and then introduce 3 approaches that I was put in
contact with over the last year, DCI, EBI and CQRS. This post is an
introduction to a series about this approaches.</p>
</div>
<p>I mentally divide the world of programming into two large parts:</p>
<ol class="arabic simple">
<li>Library and system programming</li>
<li>business applications</li>
</ol>
<p>The first produces code solving technical problems, often in a beautiful and
dedicated way. The second regularly produces mess, hopefully still
serving customers by optimizing their business. This differentiation is an
exaggeration, but from my experience its far easier to run a greenfield business
project into the ground than a new library.</p>
<p>There has to be a reason why so many programmers dedicate much free time to
open source projects. It might be empirical prove, that all our business
projects don’t make us happy at the end of the day and we have to show
ourselves that we can do better.</p>
<p>I enjoy writing business applications more than libraries, but they are also
much more difficult to get right in both social and technical dimensions.  One
motivational driver of <a class="reference external" href="https://github.com/beberlei">my open source activities</a> always was to simplify the technical dimension
of OOP business applications.</p>
<div class="section" id="my-personal-list-of-annoyances">
<h2>My Personal List of Annoyances</h2>
<p>This blog post is not about blaming customers (as the usual suspect), its about
finding the problems in usual OOP code of business systems from my experience
with PHP projects. To keep things short, I will list my <em>personal</em> list of
technical annoyances in business projects in no particular order. These are
highly subjective points.</p>
<ul class="simple">
<li>Getter/Setter Madness of Objects that are used to store data into
databases. Leading to huge objects that are essentially just meaningless
stores of data.</li>
<li>Updating complex object graphs from user input.</li>
<li>Separation of model, controller and views, especially when dealing with
forms. This is very complicated to achieve.</li>
<li>Lazy Loading and Query performance problems when using an ORM. Additionally
replacing parts of the views with hand-crafted SQL is often difficult and/or
time intensive, when already using an ORM.</li>
<li>Inability to decouple code that was written with CRUD (generators and
utilities) in mind towards more domain driven code, when the requirements
change.</li>
<li>Dependency mess leading to hard to test code, generally leading to untested
applications. Too often frameworks create huge dependencies that
make your domain model messy and complex to mock in tests.</li>
<li>Focus on synchronous request/response handling makes later usage of message
queues very complicated and expensive to refactor towards.</li>
<li>Tight coupling of model against the framework code.</li>
<li>Junior developers have too much freedom, when there is not much structure in
the code, but rather just a big ball of mud. Additionally with the tight
coupling of so many components, junior developers get easily lost in the code
and produce unexpected side-effects.</li>
<li>Use-cases easily span more than 5 classes. To grasp the interaction you have
to keep lots of code in your head, especially complicated for junior
developers again. As they cannot really work on a problem in isolation.</li>
<li>Constant violations of <a class="reference external" href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29">SOLID</a> principles
due to framework or persistence requirements.</li>
<li>Compared to library development, user-facing applications often have much
higher coupling between classes and namespaces. In libraries its often easy
to find different concerns, but in applications they seem hard to divide for
developers.</li>
<li>In combination with a rich javascript client, requirements to update objects
through their CRUD API produces concurrency and lost-update hell, that
dynamic server-side applications could mostly avoid before.</li>
</ul>
<p>Essentially if you work in a tight schedule, project based environment where
the decision makers sell rapid application development and prototyping, then you
often have only one, maybe one and a half attempts to get the big picture
right. From that moment on you have to build on that decision and hope for the
best.</p>
<p>We have tried not to go the RAD+CRUD tools ways in several projects, to escape
the problems listed above. But without changes in your mindest you end up with
hand written mess, compared to getting there with tools.</p>
<p>Specifically <a class="reference external" href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a> applied naively can make
the problem even worse. It easily leads to lasagna code, where you have layers
of layers that are very hard to understand. Personally I prefer spaghetti code
over lasagna code, because its comparatively simpler to understand.</p>
</div>
<div class="section" id="finding-new-approaches">
<h2>Finding new Approaches</h2>
<p>Rather than to embrace the suck and dive deeper into CRUD architectures, I felt
there has to be some solution to organize business models structurally to avoid
all (or most) of these problems. In the PHP world with <a class="reference external" href="http://www.symfony.com">Symfony2</a> and <a class="reference external" href="http://www.doctrine-project.org">Doctrine2</a>
you have a powerful toolbox to avoid many of the problems above, but it is
still not simple to write clean object oriented applications.</p>
<p>After years of participation in both open source projects I still feel there is
a missing puzzle piece, to reach a clean separation of all the model concerns
from framework and persistence.</p>
<p>At some point I would really like to close the gap between desired technical
state of a project and the state it is actually in. I know there is no size
fits all solution, but I fell a checklist of architectural patterns with pro
and con arguments allows me to adjust the expectations about how a system looks
in the end.</p>
<p>Thanks to <a class="reference external" href="https://twitter.com/go_oh">Gordon</a>, <a class="reference external" href="https://twitter.com/spriebsch">Stefan</a> and <a class="reference external" href="https://twitter.com/tom_noise">Thomas</a>
I was introduced to several approaches to OO application design that I
started to explore in the past last months:</p>
<ul class="simple">
<li><a class="reference external" href="http://en.wikipedia.org/wiki/Data,_context_and_interaction">Data, Context, Interaction (DCI)</a> - which Gordon
studied a lot</li>
<li><a class="reference external" href="http://alistair.cockburn.us/Hexagonal+architecture">Entity, Boundary, Interactor (EBI)</a>, also called Hexagonal
architecture or “Ports and adapters”. Gained popularity after <a class="reference external" href="http://www.confreaks.com/videos/759-rubymidwest2011-keynote-architecture-the-lost-years">Uncle Bobs talk
at Ruby Midwest</a>
last year.</li>
<li><a class="reference external" href="http://en.wikipedia.org/wiki/Command-query_separation">Command-Query-Responsibility-Segregation (CQRS)</a> well described in a
<a class="reference external" href="http://www.udidahan.com/2009/12/09/clarified-cqrs/">blog post by Udi Dahan</a> and in a hands on <a class="reference external" href="http://www.viddler.com/v/dc528842">one
day video class</a> by Greg Young.</li>
</ul>
<p>They are not new and have all been around for several years already. I would
describe all three of them as architectural design patterns, though some people
might probably disagree with this classification. All three approaches make
you think about application development beyond just “service layers” in
radically new ways. All three have helped me rethink business applications in
different ways.</p>
<p>In the next weeks I will talk about each of these approaches individually, show
some examples and then wrap up my thoughts about all of them.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Gordon and I will talk about this topic on the <a class="reference external" href="http://www.froscon.de/en/home/">Free and Open Source
Conference</a> in Sankt Augustin Germany on
25th/26th August of 2012. Feel free to drop by and discuss this topic!</p>
</div>
</div>
</div>]]></description>
            <category><![CDATA[ PHP ]]></category>
            <pubDate>Sat, 11 Aug 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/06/03/setting_up_development_machines_with_puppet.html</link>
            <guid>http://www.whitewashing.de/2012/06/03/setting_up_development_machines_with_puppet.html</guid>
            <title><![CDATA[Setting up Development Machines with Puppet]]></title>
            <description><![CDATA[<div class="section" id="setting-up-development-machines-with-puppet">
<h1>Setting up Development Machines with Puppet</h1>
<p>I wrote <a class="reference external" href="/2012/05/31/virtual_machines_with_vagrant__veewee_and_puppet.html">about Vagrant</a> last week and
mentioned to talk about <a class="reference external" href="http://puppetlabs.com/puppet/what-is-puppet/">Puppet</a> in the future. Before I will
dive into Puppet in combination with Vagrant I want to share my general
experiences with Puppet (beginners level, I just played with this today).</p>
<p>Puppet is a configuration management tool. It uses a declarative language to
describe how a system should look like. Upon invocation of puppet it attempts
to get the system from its current state into the desired state by installing
packages, executing programs/scripts and creating files/directories.</p>
<p>My laptop was still on Ubuntu 10.04 this morning, but for <a class="reference external" href="http://live.symfony.com">Symfony Live</a> I needed to upgrade to 12.04. This was necessary to
run a Virtualbox VM on my laptop that I built on my 12.04 desktop. Additionally
I really like the Unity desktop and wanted to get away from the Gnome that is
in 10.04.</p>
<p>After a backup and fresh installation of Ubuntu I realized how many things I
have to install to get this machine productive:</p>
<ul class="simple">
<li>LAMP stack + a bunch of other databases and services</li>
<li>Git, Svn, Hg, ..</li>
<li>Virtualbox + Vagrant</li>
<li>Vim with my Dot-Files, including Command-T which requires compilation,
and a bunch of development tools such as tree, ack-grep.</li>
<li>PHP Tools (PHPUnit, PHPCS, Xdebug, Xhprof)</li>
<li>Git with Author Information and global ignore file</li>
<li>A bunch of .bashrc initializations</li>
<li>Some open source projects I always have around (Doctrine, ...)</li>
<li>Setup automatic backup with my cloud storage provider (<a class="reference external" href="https://www.free-hidrive.com/">Strato Hidrive</a> - they support rsync)</li>
<li>and I probably forgot a bunch of tools just thinking about this today.</li>
</ul>
<p>I realized not only virtual machines, but also their hosts (my development
machines) could be automatically setup with Puppet.</p>
<p>So instead of saving my <tt class="docutils literal"><span class="pre">.bash_history</span></tt> to remember the steps I automated
them using Puppet. In Puppet you define Resources of several types, for example
Files, Packages or shell commands. You group these resources together in a
<tt class="docutils literal"><span class="pre">.pp</span></tt> file and then invoke <tt class="docutils literal"><span class="pre">puppet</span> <span class="pre">apply</span> <span class="pre">&lt;file&gt;.pp</span></tt>. You can install Puppet
via <tt class="docutils literal"><span class="pre">sudo</span> <span class="pre">apt-get</span> <span class="pre">install</span> <span class="pre">puppet</span></tt> on Ubuntu.</p>
<p>The idea is to define Puppet resources in a way that they are performed once and
then the system has this resource. This means you can run puppet as often as
you want and it will only activate the missing resources.</p>
<p>I separate the installation process into two puppet files, one that has to be
run with root <tt class="docutils literal"><span class="pre">~/.puppet/devmachine-root.pp</span></tt> and another one that has to be run with
my own user <tt class="docutils literal"><span class="pre">~/.puppet/devmachine.pp</span></tt>.</p>
<p>Because every dev-machine setup is unique, I will just show some
examples of my puppet file to get the message across:</p>
<div class="highlight-python"><pre># /home/benny/.puppet/devmachine.pp

# VIM Dot Files
vcsrepo { 'vim-dotfiles':
    path     =&gt; &quot;/home/$id/.vim&quot;,
    ensure   =&gt; present,
    provider =&gt; git,
    source   =&gt; 'https://...'
}

file { 'vim-dotfiles-symlink':
    path   =&gt; &quot;/home/$id/.vimrc&quot;,
    ensure =&gt; link,
    target =&gt; '.vim/vimrc',
    require =&gt; Vcsrepo['vim-dotfiles']
}

exec { 'vim-make-command-t':
    command =&gt; 'rake make',
    cwd     =&gt; &quot;/home/$id/.vim/bundle/Command-T&quot;,
    unless  =&gt; &quot;ls -aFlh /home/$id/.vim/bundle/Command-T|grep 'command-t.recipe'&quot;,
    require =&gt; Vcsrepo['vim-dotfiles']
}</pre>
</div>
<p>The three keywords <tt class="docutils literal"><span class="pre">vcsrepo</span></tt>, <tt class="docutils literal"><span class="pre">file</span></tt> and <tt class="docutils literal"><span class="pre">exec</span></tt> are called types. They
define what functionality should be executed by puppet. Vcsrepo is a custom
type that you can grab <a class="reference external" href="https://github.com/puppetlabs/puppetlabs-vcsrepo.git">from Github</a>.</p>
<ul class="simple">
<li>The first block uses Git to make sure that in my home directory the
<tt class="docutils literal"><span class="pre">~/.vim</span></tt> directory is a checkout of a given remote git repository.</li>
<li>The second file block makes sure that <tt class="docutils literal"><span class="pre">~/.vimrc</span></tt> points to <tt class="docutils literal"><span class="pre">~/.vim/vimrc</span></tt>
using a symlink.</li>
<li>The third block compiles the Command-T VIM plugin. Inside the
exec block you can see the unless condition. This is necessary to prevent the
command from being executed whenever <tt class="docutils literal"><span class="pre">devmachine.pp</span></tt> is executed with
puppet. The require makes sure this resource is only activated after the dotfiles
were installed.</li>
</ul>
<p>Another nice example is the configuration of Git:</p>
<div class="highlight-python"><pre># Configure Git
exec { &quot;git-author-name&quot;:
    command =&gt; 'git config --global user.name &quot;Benjamin Eberlei&quot;',
    unless =&gt; &quot;git config --global --get user.name|grep 'Benjamin Eberlei'&quot;
}

exec { &quot;git-author-email&quot;:
    command =&gt; 'git config --global user.email &quot;kontakt@beberlei.de&quot;',
    unless =&gt; &quot;git config --global --get user.email|grep 'kontakt@beberlei.de'&quot;
}

exec { &quot;git-global-ignore&quot;:
    command =&gt; &quot;git config --global core.excludesfile /home/$id/.gitignore&quot;,
    unless  =&gt; 'git config -l --global|grep excludesfile'
}

file { &quot;git-global-ignorefile&quot;:
    path =&gt; &quot;/home/$id/.gitignore&quot;,
    ensure =&gt; present,
    content =&gt; &quot;*.swo\n*.swp\n&quot;
}</pre>
</div>
<p>Here A bunch of commands is executed unless some option is already set. At last
the global .gitingore is filled with the patterns of Vim temporary files.</p>
<p>I also automated all the other steps listed above, but will spare you the
details. For the LAMP Stack + PHP I used <a class="reference external" href="https://github.com/dietervds/puppet-symfony2">this following Github repository</a> as an inspiration. It ships a
set of Puppet Modules. You can just put them into your <tt class="docutils literal"><span class="pre">~/.puppet/modules</span></tt>
folder and they are then available in any of your puppet files.</p>
<p>I can now reuse this on the different machines: desktop at home and at work and
my laptop. Whenever I install a new tool or change some configuration of my
system I can directly put this into puppet and keep the setup synchronized on
all the machines I work with.</p>
<p>You can find more detailed resources on the PuppetLabs website:</p>
<ul class="simple">
<li><a class="reference external" href="http://docs.puppetlabs.com/learning/ral.html">Tutorial</a></li>
<li><a class="reference external" href="http://docs.puppetlabs.com/references/latest/type.html">Type Reference</a></li>
<li><a class="reference external" href="docs.puppetlabs.com/puppet_core_types_cheatsheet.pdf">Type Cheat Sheet</a></li>
</ul>
</div>]]></description>
            <pubDate>Sun, 03 Jun 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/05/31/virtual_machines_with_vagrant__veewee_and_puppet.html</link>
            <guid>http://www.whitewashing.de/2012/05/31/virtual_machines_with_vagrant__veewee_and_puppet.html</guid>
            <title><![CDATA[Virtual Machines with Vagrant, Veewee and Puppet]]></title>
            <description><![CDATA[<div class="section" id="virtual-machines-with-vagrant-veewee-and-puppet">
<h1>Virtual Machines with Vagrant, Veewee and Puppet</h1>
<p>I have been playing with Vagrant these last days, a tool to automate Virtualbox
VM management very efficiently. Being always late to new technologies
investigating Vagrant now felt about right. I am using Virtualbox for
virtualization for about a year now but have build all my boxes manually. I
have these machines setup:</p>
<ul class="simple">
<li>Windows 7</li>
<li>Ubuntu with lots of crazy PHP builds</li>
<li>Ubuntu with Oracle, PostgreSQL for Doctrine Unit-Tests</li>
</ul>
<p>The main benefit from this is that I don’t have to clutter my main machine with
packages and dependencies that might potentially break.</p>
<p>To benefit from Virtualization on a larger scale I wanted to investigate
automation of box-building and was pointed to <a class="reference external" href="http://www.vagrantup.com">Vagrant</a>. This is a ruby tool that allows to copy and
modify virtualboxes on the fly. You define a basebox and inherit from this box
in your projects. Whenever you work on the project you start a copy of this
basebox and install more system-dependencies using Chef or Puppet.
That allows you to put the VM into a defined state just for this project. No
matter how many different and weird dependencies you need, they will always be
in this VM that is just created for the project and destroyed at the end of the
day.</p>
<p>I am using Ubuntu (currently 12.04) and tried starting with the Vagrant
example.  It fails, because their example box uses a more current Virtualbox
Guest Additions. To be able to use vagrant, you need a basebox with the
virtualbox and guest additions versions matching correctly.</p>
<p>To build your own Virtualbox you can use the Vagrant plugin <a class="reference external" href="https://github.com/jedi4ever/veewee">Veewee</a>. Install it from Github to get
all the latest VM templates:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>git clone https://github.com/jedi4ever/veewee.git
<span class="nv">$ </span><span class="nb">cd </span>veewee
<span class="nv">$ </span>sudo gem install bundler
<span class="nv">$ </span>sudo bundle install
<span class="nv">$ </span><span class="nb">alias </span><span class="nv">vagrant</span><span class="o">=</span><span class="s2">&quot;bundle exec vagrant&quot;</span>
</pre></div>
</div>
<p>You need Ruby and Gems installed for this to work. Veewee can be installed
using Gems, but this not necessarily gives you the version with the most recent
templates that match your own operating system version.</p>
<p>Now lets define our own basebox definition and copy from an existing template
that Veewee provides:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>vagrant basebox define <span class="s1">'beberlei-ubuntu-12.04-i386-php'</span> <span class="s1">'ubuntu-server-12.04-i386'</span>
</pre></div>
</div>
<p>This creates a copy from the default ubuntu server template into a folder
<cite>definitions/beberlei-ubuntu-12.04-i386-php</cite>. You can start modifying the files
in there to adjust the build process of the virtual machine image. For me its
important to modify the definitions.rb and add the following, otherwise
building the VMs fails:</p>
<div class="highlight-bash"><div class="highlight"><pre>:virtualbox <span class="o">=</span>&gt; <span class="o">{</span> : <span class="nv">vm_options</span> <span class="o">=</span>&gt; <span class="o">[</span><span class="s2">&quot;pae&quot;</span> <span class="o">=</span>&gt; <span class="s2">&quot;on&quot;</span><span class="o">]}</span>,
</pre></div>
</div>
<p>You can then open up the postinstall.sh and install more packages that you need
in your personal basebox. For example a LAMP stack. Do this right after the
lines that do <cite>apt-get install -y</cite>:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nb">export </span><span class="nv">DEBIAN_FRONTEND</span><span class="o">=</span>noninteractive
apt-get -y install php5 php5-cli php5 mysql-server-5.5 libapache2-mod-php5
</pre></div>
</div>
<p>If you are done you can start building a virtualbox image with:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>vagrant basebox build
</pre></div>
</div>
<p>Make sure not to start typing in the console window that open ups. It is
automatically controlled from a ruby script and every change to the keysequence
breaks the building. This step takes a while. (Enough to write a blog post
while watching a boring football game for example).</p>
<p>When this is done, you can verify and export the VM into virtualbox/vagrant.</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span>veewee vbox validate <span class="s1">'beberlei-ubuntu-12.04-i386-php'</span>
<span class="nv">$ </span>vagrant basebox <span class="nb">export</span> <span class="s1">'beberlei-ubuntu-12.04-i386-php'</span>
<span class="nv">$ </span>vagrant box add <span class="s1">'beberlei-ubuntu-12.04-i386-php'</span> <span class="s1">'beberlei-ubuntu-12.04-i386-php.box'</span>
</pre></div>
</div>
<p>Now this box is also available as Vagrant base box. For example in a project
that we want to use with vagrant, do:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="nv">$ </span><span class="nb">cd </span>myproject/
<span class="nv">$ </span>vagrant init <span class="s1">'beberlei-ubuntu-12.04-i386-php'</span>
<span class="nv">$ </span>vagrant up
<span class="nv">$ </span>vagrant ssh
</pre></div>
</div>
<p>Although the blog-title suggests it, Puppet hasn’t been used much up to this
point. The use of puppet with Vagrant will be part of a next blog post.</p>
</div>]]></description>
            <pubDate>Thu, 31 May 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/05/26/doctrine_goes_mit.html</link>
            <guid>http://www.whitewashing.de/2012/05/26/doctrine_goes_mit.html</guid>
            <title><![CDATA[Doctrine switches from LGPL to MIT]]></title>
            <description><![CDATA[<div class="section" id="doctrine-switches-from-lgpl-to-mit">
<h1>Doctrine switches from LGPL to MIT</h1>
<blockquote>
<div>tl;dr We moved all the Doctrine PHP projects from LGPL to MIT license
successfully in roughly 4 weeks. For that we used a small web-based tool to
ask the permission of 358 authors that contributed in the last 6 years.</div></blockquote>
<p>The <a class="reference external" href="http://www.doctrine-project.org">Doctrine project</a> has been LGPL
licensed since it was started in 2006. When I first started contributing in the
project late in 2009 we were constantly asked about changing the license to a
permissive license such as <a class="reference external" href="http://en.wikipedia.org/wiki/MIT_License">MIT</a> or
New-BSD.  My subjective feeling is that there are much more libraries with
permissive licenses than 10 years ago. And there are others that <a class="reference external" href="http://news.cnet.com/8301-13556_3-20071811-61/the-open-source-license-landscape-is-changing/">back my
feeling up with facts</a>.
The fear of getting screwed when using a permissive license has probably
declined in favor of the benefits. <a class="reference external" href="http://pooteeweet.org/blog/2084">As Lukas puts it</a>:</p>
<blockquote>
<div>Maybe with enough experience you start to realize that it happens close to
never that a proprietary fork of an open source project ends up outpacing
the original project.</div></blockquote>
<p>We wanted all the benefits of permissive licenses as well.  So at the beginning
of this year we as Doctrine project first started to investigate how the task
of switching the license could be done. After a short email with the <a class="reference external" href="http://www.fsf.org">FSF</a> it was clear that we had to get the approval of every
single committer or remove their code.</p>
<p>VLC <a class="reference external" href="http://www.videolan.org/press/lgpl.html">successfully attempted a license change</a> last year from GPL to LGPL, so we
we’re hopeful to get this done. After discussing with Lukas we came up with the
idea of a tool that helps this process, so <a class="reference external" href="http://dlm.beberlei.de">I wrote it</a>. It features:</p>
<ul class="simple">
<li>Import of all commits from one or many Github projects</li>
<li>Aggregation of commits to authors based on e-mail address from Git log</li>
<li>Status approved/not-approved for every author.</li>
<li>An e-mail engine to send a request for approval to every author using
<a class="reference external" href="http://www.mailgun.net">the awesome Mailgun service</a>, who has not approved
yet. We use Mailgun for fun and to have a way to act on bounces easily.</li>
<li>Admin functionality to mark commits as “trivial or deleted”.</li>
<li>An audit trail to account for all changes and who has done them.</li>
<li>Symfony2/Doctrine2 application with debian packaging using FPM.</li>
</ul>
<p>This project is not yet open-sourced but will be when I have some time to clean
up the hardcoded passwords and write a small README on how to adjust the
templates.</p>
<p>After importing the commits of all the LGPL licensed Doctrine projects we
realized that we have 358 unique committers and about 40-50 without an e-mail
address (from the old SVN days). So we started googling for nicknames and
eventually collected all e-mail addresses except maybe 6-8 missing ones.</p>
<p>Now after 4 weeks of bi-weekly e-mail reminders, everyone except 16 committers have
accepted the license change. No single person refused the change. All commits
of the 16 people left we’re luckily not part of the code base anymore when we
completely rewrote Doctrine 2 or trivial one-line changes.</p>
<p>I am very happy to announce that Doctrine is now an MIT licensed project. Have
fun with it.</p>
</div>]]></description>
            <pubDate>Sat, 26 May 2012 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2012/02/25/symfony2_controller_testing.html</link>
            <guid>http://www.whitewashing.de/2012/02/25/symfony2_controller_testing.html</guid>
            <title><![CDATA[Symfony2 Controller Testing without Application]]></title>
            <description><![CDATA[<div class="section" id="symfony2-controller-testing-without-application">
<h1>Symfony2 Controller Testing without Application</h1>
<p>Controller testing using the WebTestCase requires a Symfony Kernel and with
that a complete application. However you can just ship your own simple kernel
with just the dependencies necessary to test your application. This way you can
easily create functional tests for bundles without the bundle requiring an
application.</p>
<div class="section" id="create-a-testkernel">
<h2>Create a TestKernel</h2>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="c1">// Tests/Controller/App/AppKernel.php</span>

<span class="k">use</span> <span class="nx">Symfony\Component\HttpKernel\Kernel</span><span class="p">;</span>
<span class="k">use</span> <span class="nx">Symfony\Component\Config\Loader\LoaderInterface</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">AppKernel</span> <span class="k">extends</span> <span class="nx">Kernel</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">registerBundles</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$bundles</span> <span class="o">=</span> <span class="k">array</span><span class="p">(</span>
            <span class="c1">// Dependencies</span>
            <span class="k">new</span> <span class="nx">Symfony\Bundle\FrameworkBundle\FrameworkBundle</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">Symfony\Bundle\SecurityBundle\SecurityBundle</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">Symfony\Bundle\MonologBundle\MonologBundle</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">Symfony\Bundle\TwigBundle\TwigBundle</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle</span><span class="p">(),</span>
            <span class="k">new</span> <span class="nx">JMS\SerializerBundle\JMSSerializerBundle</span><span class="p">(</span><span class="nv">$this</span><span class="p">),</span>
            <span class="k">new</span> <span class="nx">FOS\RestBundle\FOSRestBundle</span><span class="p">(),</span>
            <span class="c1">// My Bundle to test</span>
            <span class="k">new</span> <span class="nx">Beberlei\WorkflowBundle\BeberleiWorkflowBundle</span><span class="p">(),</span>
        <span class="p">);</span>

        <span class="k">return</span> <span class="nv">$bundles</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">registerContainerConfiguration</span><span class="p">(</span><span class="nx">LoaderInterface</span> <span class="nv">$loader</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// We don't need that Environment stuff, just one config</span>
        <span class="nv">$loader</span><span class="o">-&gt;</span><span class="na">load</span><span class="p">(</span><span class="nx">__DIR__</span><span class="o">.</span><span class="s1">'/config.yml'</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="creating-the-config-yml">
<h2>Creating the config.yml</h2>
<div class="highlight-yaml"><pre># Tests/Controller/App/config.yml
framework:
    secret:          secret
    charset:         UTF-8
    test: ~
    router:          { resource: &quot;%kernel.root_dir%/routing.yml&quot; }
    form:            true
    csrf_protection: true
    validation:      { enable_annotations: true }
    templating:      { engines: ['twig'] }
    session:
        auto_start:     false
        storage_id: session.storage.filesystem

monolog:
    handlers:
        main:
            type:         fingers_crossed
            action_level: error
            handler:      nested
        nested:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug</pre>
</div>
</div>
<div class="section" id="creating-the-routing-yml">
<h2>Creating the routing.yml</h2>
<div class="highlight-yaml"><div class="highlight"><pre><span class="c1"># Tests/Controller/App/routing.yml</span>
<span class="l-Scalar-Plain">BeberleiWorkflowBundle</span><span class="p-Indicator">:</span>
    <span class="l-Scalar-Plain">resource</span><span class="p-Indicator">:</span> <span class="s">&quot;@BeberleiWorkflowBundle/Controller/&quot;</span>
    <span class="l-Scalar-Plain">type</span><span class="p-Indicator">:</span>     <span class="l-Scalar-Plain">annotation</span>
    <span class="l-Scalar-Plain">prefix</span><span class="p-Indicator">:</span>   <span class="l-Scalar-Plain">/</span>
</pre></div>
</div>
</div>
<div class="section" id="adding-a-phpunit-bootstrap">
<h2>Adding a PHPUnit bootstrap</h2>
<p>I assume the setup that Henrik described in his “<a class="reference external" href="http://henrik.bjrnskov.dk/travis-and-composer-sitting-in-a-tree/">Travis &amp; Composer sitting in a
Tree K-I-S-S-I-N-G” blog post</a>.</p>
<p>His setup is missing the spl_autoload_register() call in the bootstrap file
though.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="c1">// Tests/bootstrap.php</span>
<span class="nv">$loader</span> <span class="o">=</span> <span class="o">@</span><span class="k">include</span> <span class="nx">__DIR__</span> <span class="o">.</span> <span class="s1">'/../vendor/.composer/autoload.php'</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nv">$loader</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">die</span><span class="p">(</span><span class="s">&lt;&lt;&lt;'EOT'</span>
<span class="s">You must set up the project dependencies, run the following commands:</span>
<span class="s">wget http://getcomposer.org/composer.phar</span>
<span class="s">php composer.phar install</span>
<span class="s">EOT</span>
    <span class="p">);</span>
<span class="p">}</span>
<span class="nx">\Doctrine\Common\Annotations\AnnotationRegistry</span><span class="o">::</span><span class="na">registerLoader</span><span class="p">(</span><span class="k">array</span><span class="p">(</span><span class="nv">$loader</span><span class="p">,</span> <span class="s1">'loadClass'</span><span class="p">));</span>

<span class="nb">spl_autoload_register</span><span class="p">(</span><span class="k">function</span><span class="p">(</span><span class="nv">$class</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="mi">0</span> <span class="o">===</span> <span class="nb">strpos</span><span class="p">(</span><span class="nv">$class</span><span class="p">,</span> <span class="s1">'Beberlei\\WorkflowBundle\\'</span><span class="p">))</span> <span class="p">{</span>
        <span class="nv">$path</span> <span class="o">=</span> <span class="nx">__DIR__</span><span class="o">.</span><span class="s1">'/../'</span><span class="o">.</span><span class="nb">implode</span><span class="p">(</span><span class="s1">'/'</span><span class="p">,</span> <span class="nb">array_slice</span><span class="p">(</span><span class="nb">explode</span><span class="p">(</span><span class="s1">'\\'</span><span class="p">,</span> <span class="nv">$class</span><span class="p">),</span> <span class="mi">2</span><span class="p">))</span><span class="o">.</span><span class="s1">'.php'</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nb">stream_resolve_include_path</span><span class="p">(</span><span class="nv">$path</span><span class="p">))</span> <span class="p">{</span>
            <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">require_once</span> <span class="nv">$path</span><span class="p">;</span>
        <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">});</span>
</pre></div>
</div>
<p>That means your bundle should have a composer.json that loads all the
dependencies.</p>
</div>
<div class="section" id="modifying-the-phpunit-xml-dist">
<h2>Modifying the phpunit.xml.dist</h2>
<p>We have to tell the WebTestCase base class where to find this kernel:</p>
<div class="highlight-xml"><div class="highlight"><pre><span class="c">&lt;!-- phpunit.xml.dist --&gt;</span>
<span class="nt">&lt;phpunit</span> <span class="na">bootstrap=</span><span class="s">&quot;Tests/bootstrap.php&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;php&gt;</span>
        <span class="nt">&lt;server</span> <span class="na">name=</span><span class="s">&quot;KERNEL_DIR&quot;</span> <span class="na">value=</span><span class="s">&quot;Tests/Controller/App&quot;</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/php&gt;</span>
<span class="nt">&lt;/phpunit&gt;</span>
</pre></div>
</div>
<p>Now just run your web-test cases.</p>
<p>If you want to debug the logging happening inside the Kernel just comment out
the Monolog lines to get the log-messages printed to the screen.</p>
<p>You have to add the <cite>Tests/App/cache</cite> and <cite>Tests/App/logs</cite> to your version
control ignore files.</p>
</div>
</div>]]></description>
            <pubDate>Sat, 25 Feb 2012 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/02/07/resources-for-a-php-and-hudson-ci-integration.html</link>
            <guid>http://www.whitewashing.de/2010/02/07/resources-for-a-php-and-hudson-ci-integration.html</guid>
            <title><![CDATA[Resources for a PHP and Hudson CI Integration]]></title>
            <description><![CDATA[<div class="section" id="resources-for-a-php-and-hudson-ci-integration">
<h1>Resources for a PHP and Hudson CI Integration</h1>
<p>Yesterday I finally had the time to setup my first continuous
integration environment. Possible solutions for CI are
<a class="reference external" href="http://phpundercontrol.org/about.html">phpUnderControl</a>,
<a class="reference external" href="http://www.hudson-ci.org">Hudson</a> or
<a class="reference external" href="http://www.arbitracker.org">Arbit</a>. Although phpUnderControl is the
most wide-spread, but from I heard complex to setup/maintain, solution
[STRIKEOUT:supposedly a hack] and Arbit just in an early Alpha I decided
to give Hudson a shoot. Another reason for this decision, I heard it has
a simple plugin architecture and is easy to install and use.
Additionally Hudson is easily integrated into
<a class="reference external" href="http://www.netbeans.org">Netbeans</a> and
<a class="reference external" href="http://www.redmine.org">Redmine</a>, and I use both tools regularly in
development.</p>
<p>My motivation to dive into CI is easily explained. I just never felt it
was necessary to add a continuous integration environment to my projects,
since I had one or two simple bash scripts that did the job. In general
this is rather annoying, because they mostly only run PHPUnit and have
to be done using a cronjob or manually, without any real process of
notification. Additionally you have no way to navigate the test-results,
code-coverage and no history of the last builds. For projects like
<a class="reference external" href="http://www.doctrine-project.org">Doctrine 2</a> we have the additional
requirement to support 4 different database platforms, i.e. 4 different
PHPUnit configurations. Currently that is solved by me using a Bash
script that iterates over the configuration file names and invokes
PHPUnit.</p>
<p>There are already some awesome sources how to get Hudson and PHP
working. I’ll list them here:</p>
<ul class="simple">
<li><a class="reference external" href="http://www.flickr.com/photos/sebastian_bergmann/sets/72157622541690849/">Sebastian Bergmann’s Howto in
Screenshots</a></li>
<li><a class="reference external" href="http://luhman.org/blog/2009/12/16/installing-hudson-phing-phpunit-and-git-ubuntu">David Luhman’s series on PHP and
Hudson</a></li>
<li><a class="reference external" href="http://blog.jepamedia.org/2009/10/28/continuous-integration-for-php-with-hudson/">Justin Palmers Guide to install PHP and Hudson (With
Screenshots)</a></li>
</ul>
<p>All those guides are already awesome and I would recommend choosing one
of those to install Hudson, I think i can’t add anything new to those. I
have used Sebastians Howto, however i also like the third one. David
Luhmans guide adds lots of details that are important to get the
different parts of a build process to work.</p>
<p>Now what these tutorials all do is that they use a bash command to
execute the build process or specify an Ant Build file. However there
is also a Phing Build process plugin for Hudson that allows to specify
the build.xml targets to execute in the process. From the “Available
Plugins” list you can choose the “Phing plugin”.</p>
<p>After installation you have to configure the Phing install. The <a class="reference external" href="http://wiki.hudson-ci.org/display/HUDSON/Phing+Plugin">Phing
Plugin Wiki
Page</a> shows how
to do this. You have to go to “Manage Hudson” =&gt; “Configure System” and
look for Phing. There you find the dialog to configure your phing
installations.</p>
<p>In the context of choosing a build script for your project you can now
choose “Phing” instead of Ant:</p>
<div class="figure align-center">
<img alt="" src="http://www.flickr.com/photos/sebastian_bergmann/4046549930/in/set-72157622541690849/"/>
</div>
<p>You can enter the targets to build, for example on my local Hudson
instance I only execute “test” for Doctrine 2, since I am not interested
in the building and deployment onto the PEAR channel at this development
stage.</p>
<p>From inside Netbeans you can then start builds by pointing to the Hudson
instance. See this tutorial by one of the <a class="reference external" href="http://blogs.sun.com/joshis/entry/hudson_integration_in_netbeans_6">Hudson + Netbeans
Developers</a>.
You can then start all the builds from inside Netbeans and be notified
of the success or failure.</p>
</div>]]></description>
            <pubDate>Sun, 07 Feb 2010 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/05/02/testing-database-locks-with-phpunit-and-gearman.html</link>
            <guid>http://www.whitewashing.de/2010/05/02/testing-database-locks-with-phpunit-and-gearman.html</guid>
            <title><![CDATA[Testing Database Locks with PHPUnit and Gearman]]></title>
            <description><![CDATA[<div class="section" id="testing-database-locks-with-phpunit-and-gearman">
<h1>Testing Database Locks with PHPUnit and Gearman</h1>
<p>For the Beta 2 release of <a class="reference external" href="http://www.doctrine-project.org">Doctrine
2</a> we plan to integrate pessimistic
Database-level locks across all the supported vendors (MySQL, Oracle,
PostgreSql, IBM DB2 so far). This means row-level locking as defined in
the ANSI SQL Standard using “SELECT .. FOR UPDATE” will be available
optionally in DQL Queries and Finder methods. The Implementation of this
extension to SELECT statements is rather trivial, however functional
testing of this feature is not.</p>
<p>A general approach would look like this:</p>
<ol class="arabic simple">
<li>Run Query 1 and 2 with FOR UPDATE into the background</li>
<li>Have both queries lock the row for a specified time x (using sleep)</li>
<li>Verify that one of the two processes/threads runs approximately 2*x
the lock time.</li>
</ol>
<p>Since PHP does not support process forking or threads naturally you run
into a serious problem. How do you execute two database queries in
parallel and verify that indeed one query is locking read access for the
second one?</p>
<p>Side note: There are some drawbacks to this testing approach. It could
be that one background threads finishes the lock sleep already when the
second just starts. The locking would work in these cases, however the
lock time would not nearly be 2*x seconds, producing a test-failure. We
are talking about a functional test though and I will accept a failure
from time to time just to be 99% sure that locking works.</p>
<p>Solving this problem with Gearman provides a pretty nice “real-world”
example for the Job-Server that I wanted to share. This blog post
contains a stripped down code-example from the Doctrine 2 testsuite. If
you are interested, you can see the complete Gearman Locking Tests in
<a class="reference external" href="http://github.com/beberlei/doctrine2/tree/lock-support/tests/Doctrine/Tests/ORM/Functional/Locking/">on
GitHub</a>.</p>
<p>Gearman allows to register worker processes with the job-server and
offers clients to execute jobs on those workers in parallel. After
installing the Gearman job-server and PHP pecl/gearman extension
(<a class="reference external" href="http://toys.lerdorf.com/archives/51-Playing-with-Gearman.html">Rasmus Lerdorf has a post on
installation</a>)
we can go on writing our locking tests with Gearman.</p>
<p>The first bit is the worker, a PHP script that tries to acquire a
database lock and then sleeps for a second. The return value of this
script is the total time required for acquiring the lock and sleeping.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class LockAgentWorker</span>
<span class="x">{</span>
<span class="x">    public function findWithLock($job)</span>
<span class="x">    {</span>
<span class="x">        $fixture = $this-&gt;processWorkload($job); // setup doctrine in here</span>

<span class="x">        $s = microtime(true);</span>
<span class="x">        $this-&gt;em-&gt;beginTransaction();</span>

<span class="x">        $entity = $this-&gt;em-&gt;find($fixture['entityName'], $fixture['entityId'], $fixture['lockMode']);</span>

<span class="x">        sleep(1);</span>
<span class="x">        $this-&gt;em-&gt;rollback(); // clean up doctrine</span>

<span class="x">        return (microtime(true) - $s);</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>The glue-code for the worker script contains of the registering of the
worker method with the job-server and a simple infinite loop:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">$lockAgent = new LockAgentWorker();</span>

<span class="x">$worker = new \GearmanWorker();</span>
<span class="x">$worker-&gt;addServer();</span>
<span class="x">$worker-&gt;addFunction(&quot;findWithLock&quot;, array($lockAgent, &quot;findWithLock&quot;));</span>

<span class="x">while($worker-&gt;work()) {</span>
<span class="x">    if ($worker-&gt;returnCode() != GEARMAN_SUCCESS) {</span>
<span class="x">        break;</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>We need two running workers for this to work, since one worker only
processes one task at a time. Just open up two terminals and launch the
php scripts. They will wait for their first task to process.</p>
<p>Now we need to write our PHPUnit TestCase, which will contain a
GearmanClient to execute two of the “findWithLock” in parallel. Our
locking assertion will work like this:</p>
<ol class="arabic simple">
<li>Register two tasks for the “findWithLock” method that access the same
database row.</li>
<li>Register a completed callback using
“GearmanClient::setCompleteCallback()” that collects the run-time of
the individual workers.</li>
<li>Execute this tasks in parallel using “GearmanClient::runTasks()”.</li>
<li>Assert that the maximum run-time is around 2 seconds (since each
worker sleeps 1 second)</li>
</ol>
<p>The code for this steps could look like:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class GearmanLockTest extends \Doctrine\Tests\OrmFunctionalTestCase</span>
<span class="x">{</span>
<span class="x">    private $gearman = null;</span>
<span class="x">    private $maxRunTime = 0;</span>
<span class="x">    private $articleId;</span>

<span class="x">    public function testLockIsAcquired()</span>
<span class="x">    {</span>
<span class="x">        // .. write fixture data into the database</span>

<span class="x">        $gearman = new \GearmanClient();</span>
<span class="x">        $gearman-&gt;addServer();</span>
<span class="x">        $gearman-&gt;setCompleteCallback(array($this, &quot;gearmanTaskCompleted&quot;));</span>

<span class="x">        $workload = array(); // necessary workload data to configure workers</span>
<span class="x">        $gearman-&gt;addTask(&quot;findWithLock&quot;, serialize($workload));</span>
<span class="x">        $gearman-&gt;addTask(&quot;findWithLock&quot;, serialize($workload));</span>

<span class="x">        $gearman-&gt;runTasks();</span>

<span class="x">        $this-&gt;assertTrue($this-&gt;maxRunTime &gt;= 2);</span>
<span class="x">    }</span>

<span class="x">    public function gearmanTaskCompleted($task)</span>
<span class="x">    {</span>
<span class="x">        $this-&gt;maxRunTime = max($this-&gt;maxRunTime, $task-&gt;data());</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>Now if both workers are waiting for processing the task we can run this
test and get a green bar for a working lock support.</p>
</div>]]></description>
            <pubDate>Sun, 02 May 2010 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/01/08/immutable-datetime-objects.html</link>
            <guid>http://www.whitewashing.de/2010/01/08/immutable-datetime-objects.html</guid>
            <title><![CDATA[Immutable DateTime Objects]]></title>
            <description><![CDATA[<div class="section" id="immutable-datetime-objects">
<h1>Immutable DateTime Objects</h1>
<p>One serious drawback of <a class="reference external" href="http://de.php.net/DateTime">PHPs DateTime
extension</a> is the mutability of its
instances. It can lead to serious bugs if a DateTime instance is passed
between different functions and is modified at unexpected places.
Additionally this possibly rules out several optimizations for scripts
that make very heavy use of dates and could share references to equal
timestamps.</p>
<p><strong>Warning:</strong> All the code assumes that you work with one timezone only!</p>
<p>The following code is an immutable version of PHP’s DateTime. All setter
methods throw an exception and add(),sub() and modify() clone the
current instance, apply the operation and return the new instance.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">namespace</span> <span class="nx">Whitewashing\DateTime</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">DateTime</span> <span class="k">extends</span> <span class="nx">\DateTime</span>
<span class="p">{</span>
    <span class="sd">/**</span>
<span class="sd">     * To prevent infinite recursions</span>
<span class="sd">     *</span>
<span class="sd">     * @var bool</span>
<span class="sd">     */</span>
    <span class="k">private</span> <span class="k">static</span> <span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">add</span><span class="p">(</span><span class="nv">$interval</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
            <span class="nv">$newDate</span> <span class="o">=</span> <span class="k">clone</span> <span class="nv">$this</span><span class="p">;</span>
            <span class="nv">$newDate</span><span class="o">-&gt;</span><span class="na">add</span><span class="p">(</span><span class="nv">$interval</span><span class="p">);</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>
            <span class="k">return</span> <span class="nv">$newDate</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="k">parent</span><span class="o">::</span><span class="na">add</span><span class="p">(</span><span class="nv">$interval</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">modify</span><span class="p">(</span><span class="nv">$modify</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
            <span class="nv">$newDate</span> <span class="o">=</span> <span class="k">clone</span> <span class="nv">$this</span><span class="p">;</span>
            <span class="nv">$newDate</span><span class="o">-&gt;</span><span class="na">modify</span><span class="p">(</span><span class="nv">$modify</span><span class="p">);</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>
            <span class="k">return</span> <span class="nv">$newDate</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="k">parent</span><span class="o">::</span><span class="na">modify</span><span class="p">(</span><span class="nv">$modify</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">sub</span><span class="p">(</span><span class="nv">$interval</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
            <span class="nv">$newDate</span> <span class="o">=</span> <span class="k">clone</span> <span class="nv">$this</span><span class="p">;</span>
            <span class="nv">$newDate</span><span class="o">-&gt;</span><span class="na">sub</span><span class="p">(</span><span class="nv">$interval</span><span class="p">);</span>
            <span class="nx">self</span><span class="o">::</span><span class="nv">$_immutable</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span>
            <span class="k">return</span> <span class="nv">$newDate</span><span class="p">;</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="k">return</span> <span class="k">parent</span><span class="o">::</span><span class="na">sub</span><span class="p">(</span><span class="nv">$interval</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">setDate</span><span class="p">(</span><span class="nv">$year</span><span class="p">,</span> <span class="nv">$month</span><span class="p">,</span> <span class="nv">$day</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">ImmutableException</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setISODate</span><span class="p">(</span><span class="nv">$year</span><span class="p">,</span> <span class="nv">$week</span><span class="p">,</span> <span class="nv">$day</span><span class="o">=</span><span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">ImmutableException</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setTime</span><span class="p">(</span><span class="nv">$hour</span><span class="p">,</span> <span class="nv">$minute</span><span class="p">,</span> <span class="nv">$second</span><span class="o">=</span><span class="k">null</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">ImmutableException</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setTimestamp</span><span class="p">(</span><span class="nv">$timestamp</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">ImmutableException</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">setTimezone</span><span class="p">(</span><span class="nv">$timezone</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nx">ImmutableException</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="k">class</span> <span class="nc">ImmutableException</span> <span class="k">extends</span> <span class="nx">\Exception</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">parent</span><span class="o">::</span><span class="na">__construct</span><span class="p">(</span><span class="s2">&quot;Cannot modify Whitewashing\DateTime\DateTime instance, its immutable!&quot;</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Its not the prettiest code, but it works.</p>
<p>A next optimization would be a <strong>DateFactory</strong> that manages DateTime
instances by returning already existing instances for specific dates.
This is not a perfect solution, since you won’t be able to enforce a
single instance when you are using the relative descriptive dates or
when calculating with dates using add(), sub() and modify(), however for
lots of dates created from a database or other external source it might
be quite a powerful optimization depending on your use-case:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">namespace Whitewashing\DateTime;</span>

<span class="x">class DateFactory</span>
<span class="x">{</span>
<span class="x">    static private $_dates = array();</span>

<span class="x">    static public function create($hour, $minute, $second, $month, $day, $year)</span>
<span class="x">    {</span>
<span class="x">        $ts = mktime($hour, $minute, $second, $month, $day, $year);</span>
<span class="x">        if (!isset(self::$_dates[$ts])) {</span>
<span class="x">            self::$_dates[$ts] = new DateTime('@'.$ts);</span>
<span class="x">        }</span>
<span class="x">        return self::$_dates[$ts];</span>
<span class="x">    }</span>

<span class="x">    static public function createFromMysqlDate($mysqlDate)</span>
<span class="x">    {</span>
<span class="x">        list($date, $time) = explode(&quot; &quot;, $mysqlDate);</span>
<span class="x">        if($time == null) {</span>
<span class="x">            $hour = $minute = $second = 0;</span>
<span class="x">        } else {</span>
<span class="x">            list($hour, $minute, $second) = explode(&quot;:&quot;, $time);</span>
<span class="x">        }</span>
<span class="x">        list($year, $month, $day) = explode(&quot;-&quot;, $mysqlDate);</span>
<span class="x">        return self::create($hour, $minute, $second, $month, $day, $year);</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>This includes some date time calculations and date creation with
mktime() and DateTimes unix timestamp capabilities to be able to work.
Otherwise the sharing of instances could not be implemented. If you need
to create shareable instances from other formats you could just create
another creation method for it and convert the format for create() to be
used.</p>
</div>]]></description>
            <pubDate>Fri, 08 Jan 2010 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/01/10/application-lifecycle-management-and-deployment-with-pear-and-phar-revisited-update.html</link>
            <guid>http://www.whitewashing.de/2010/01/10/application-lifecycle-management-and-deployment-with-pear-and-phar-revisited-update.html</guid>
            <title><![CDATA[Application Lifecycle Management and Deployment with PEAR and PHAR (revisited) UPDATE]]></title>
            <description><![CDATA[<div class="section" id="application-lifecycle-management-and-deployment-with-pear-and-phar-revisited-update">
<h1>Application Lifecycle Management and Deployment with PEAR and PHAR (revisited) <em>UPDATE</em></h1>
<p>Some weeks ago <a class="reference external" href="http://www.whitewashing.de/blog/articles/123">I posted an
article</a> on using PEAR
and PHAR for application lifecycle management and deployment. Since then
I have gotten some feedback through comments, but also discussed the
topic with colleagues. I have also optimized the approach quite
considerably and even <a class="reference external" href="http://github.com/beberlei/pearanha">made an open-source project out of parts of
it</a> and I want to share all that
is new with you. First of all, yes the presented solution was somewhat
complex, partly because it is still a proposed idea and definitely up
for optimizations. However I am still very convinced of my approach,
something I should discuss in more detail.</p>
<p>The only other two languages I have ever programmed something in with
more than 50 lines of code are Java and C#. In both languages you can
explicitly import different dependencies like libraries and frameworks
by adding them to your application, i.e. in java you would add for
example Spring as an MVC Web layer, Hibernate as an ORM and several
other things to your project and directly bundle them in your
executable. This is very easy to configure and maintain in IDEs like
Netbeans or Eclipse (C# has the same with allowing you to attach DDLs of
libraries to your project). It also makes for a much more
straightforward deployment.</p>
<p>In the PHP world this situation was quite different (up to PHP 5.3) for
several reasons:</p>
<ul class="simple">
<li>You could not package a library into a single distributable file.</li>
<li>The PEAR installer as the only tool for updating and managing
dependencies of your application by default installs into a
system/global directory. This means dependencies your application
uses are located in a completely different location than your
application code.</li>
<li>You can’t manage multiple versions of the same package with PEAR in
this system directory, making it very hard to control servers with
different applications.</li>
<li>The global directory with your application dependencies is most often
not under version control, which makes deployment of applications
with PEAR dependencies somewhat difficult.</li>
</ul>
<p>There are some solutions to this problems:</p>
<ul class="simple">
<li>Don’t use PEAR, but put all dependencies in your version control
system.</li>
<li>Don’t use PEAR, and bundle dependencies to your code in the
build/deployment process.</li>
<li>Use PEAR like in the article described, on a per project basis.</li>
</ul>
<p>The solutions that don’t use PEAR suffer from the disadvantage that you
need to keep track of all the library and framework dependencies
yourself and upgrade them yourself. This might not be such a huge
problem from a first glance, but in my opinion many PHP applications and
projects suffer from using either no framework/library or just exactly
one. There is no real cherry-picking going on the PHP world, for example
I would really like to use Zend Framework for the general application
layout, but still use Doctrine for the Modelling and HTML Purifier for
the Output Escaping. Certain tasks might then only be solvable with the
help of eZ Components, all of which are then to some extend dependencies
of my application. With <a class="reference external" href="http://pearhub.org/">PEARHUB</a> and
<a class="reference external" href="http://pearfarm.org/">PEARFARM</a> on the horizon (<a class="reference external" href="http://blog.astrumfutura.com/archives/431-The-Democratisation-Of-PEAR-By-Pearfarm-and-Pearhub-or-About-Bloody-Time!.html">Read Padraic on this
topic</a>)
even more PHP code will be distributed using PEAR channels in the near
future. My <a class="reference external" href="http://www.whitewashing.de/blog/articles/124">immutable
DateTime</a> code for
example makes for a great little open source library that could be
distributed via PEAR, as well as
<a class="reference external" href="http://github.com/beberlei/yadif">Yadif</a> - a dependency injection
container I am using extensively.</p>
<p>Question: Are you really going to manage all these dependencies
correctly manually? Is everything up to date all the time, and
upgradeable with ease?</p>
<p>The PEAR driven solution then begins to look very desirable in this
light, however it has a considerable disadvantage: The PEAR installer
itself works on a system-wide/user-centric basis, making it impossible
to manage dependencies of several applications using only one linux
user. My little <a class="reference external" href="http://github.com/beberlei/pearanha">Pearanha</a> to the
rescue: I have taken the PEAR installer code (which is distributed with
all PHP installations across all systems) and put a new CLI tool on top
of it. Its a very simple code-generator that allows to generate a
re-configured PEAR installer script which only manages a single
application in a given directory. This approach is also used by the
symfony plugin mechanism, which internally uses the PEAR installer (did
you know?).</p>
<p>Lets revisit my blog application example <a class="reference external" href="%3Ca%20href=">from my previous PEAR
post</a>, first install from
<a class="reference external" href="http://github.com/beberlei/pearanha">Github</a> and make the “pearanha”
file executable and put it in your PATH (A PEAR Server Channel will
follow any time soon).</p>
<p>Now we need to have an existing application directory somewhere, for
example <strong>/var/www/blog</strong> and then we can put Pearanha on top of it
with:</p>
<blockquote>
<div><div class="highlight-python"><pre>benny@desktop: pearanha generate-project</pre>
</div>
</div></blockquote>
<p>You then need to specify the project base dir and then the project
style (for example Zend Framework or Manual) which prompts your for the
directory that should be used for as the vendor/library directory that
PEAR will install all the code in. You will also be prompted for a
binary/scripts directory which will then hold a new PHP file for you,
the file <strong>my_phpiranha</strong>.</p>
<p><strong>Pro Argument:</strong> Switching to Pearanha can be done at any point in your
application lifecycle. Just define an additional vendor directory for
all the dependencies to go in and generate the applications pear
installer and you are good to go.</p>
<p>The generated script is your new application specific PEAR installer and
you can begin to install all the required dependencies of your
application:</p>
<blockquote>
<div><div class="highlight-python"><pre>benny@desktop:~$ cd /var/www/blog
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha channel-discover pear.zfcampus.org
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha install zfcampus/zf-alpha
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha channel-discover htmlpurifier.org
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha install hp/HTMLPurifier
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha channel-discover pear.phpdoctrine.org
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha install pear.phpdoctrine.org/DoctrineORM-2.0.0
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha channel-discover components.ez.no
benny@desktop:/var/www/blog$ ./vendor/pear/my_pearanha install ezc/ezcGraph</pre>
</div>
</div></blockquote>
<p>All this stuff is now located in <strong>/var/www/blog/vendor</strong>. Again you can
use PEARs complete upgrade, remove and install functionality for your
application, now without the hazzle of having to create a linux user for
each project you want to manage this way, which in my opinion is a
considerable simplification. The complete application (including its
dependencies) can then be put under version control and be readily
packaged as a single executable PHAR file by your build process.</p>
<p>As a side node, I did try Pyrus instead of PEAR for the same discussed
purpose, however most of the current PEAR channels don’t validate
against Pyrus strict standards for the package.xml file. In the future
this might change and a Pyrus based application installer will then be
integrated into Pearanha.</p>
<p><strong>UPDATE:</strong> I renamed PHPiranha to Pearanha as its more appropriate.
Also after apinsteins comment on “pear config-create” I rewrote the
generate-project parts to use the config-create functionality
internally, which allowed me to throw away half of the self-written
code. Thanks!</p>
</div>]]></description>
            <pubDate>Sun, 10 Jan 2010 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/04/27/doctrine-2-beta-1-released.html</link>
            <guid>http://www.whitewashing.de/2010/04/27/doctrine-2-beta-1-released.html</guid>
            <title><![CDATA[Doctrine 2 Beta 1 released]]></title>
            <description><![CDATA[<div class="section" id="doctrine-2-beta-1-released">
<h1>Doctrine 2 Beta 1 released</h1>
<p>Today we are happy to announce that the first beta of <a class="reference external" href="http://www.doctrine-project.org/blog/doctrine-2-0-0-beta1-released">Doctrine
2</a>
has been released and we fixed 165 issues kindly reported by several
early adopters.</p>
<p>You can grab the code from the Github project:</p>
<blockquote>
<div><dl class="docutils">
<dt><a class="reference external" href="http://github.com/doctrine/doctrine2/tree/2.0.0-BETA1">http://github.com/doctrine/doctrine2/tree/2.0.0-BETA1</a></dt>
<dd>git clone git://github.com/doctrine/doctrine2.git</dd>
</dl>
</div></blockquote>
<p>Or download it from our website:</p>
<blockquote>
<div><a class="reference external" href="http://www.doctrine-project.org/download#2_0">http://www.doctrine-project.org/download#2_0</a></div></blockquote>
<p>It is our believe that Doctrine 2 brings PHP ORMs to a new level. We are
leaving behind the Active Record pattern because we think it hurts
testability, project maintainability and is not a suitable abstraction
(80/20) for models that exceed the complexity of a blog or otherwise
simple web application. Instead we implemented a pure Data Mapper
approach with help of the new Reflection functionalities of PHP 5.3, so
your Domain Objects neither have to extend a base class nor implement an
interface.</p>
<p>We also dropped most of the magical features of Doctrine 1 in favour of
a simple and standardized API that is loosely based on the <a class="reference external" href="http://en.wikipedia.org/wiki/Java_Persistence_API">Java
Persistence API</a>, a
technical standard for Object Relational Mappers. However we try not to
blindly follow the “Program PHP like Java” approach and and deviated
from JPA where applicable to make the concepts fit better into the PHP
environment, such as alternatively hydrating all results into nested
array structures for very high read performance.</p>
<p>The cornerstone of Doctrine 2 is the query language DQL. It allows to
execute queries on the object level defined by your metadata in a
similar fashion to SQL. You can even do Joins, Subselects and Aggregates
and Group Clauses in DQL, eliminating the need to circumvent ORMs for
more advanced SQL features. Nevertheless it is also possible to write
plain SQL and let Doctrine 2 hydrate the results into an object graph.</p>
<p>In the last three month since alpha 4 we have done considerable changes
and integrated lots of feedback from our users. The most notable changes
are:</p>
<ul class="simple">
<li>Allowing Constructors of your Domain Objects to have non-optional
parameters.</li>
<li>Allow to define a natural ordering of to Many Collections that is
automatically enforced trough an SQL ORDER BY statement when
retrieved from the database.</li>
<li>Shipping the Symfony Console Component to replace our own Console
Implementation</li>
<li>New DQL syntax to load objects partially, omitting potentially
expensive fields from retrieval for the current request.</li>
<li>Changes to how bi-directional have to be defined in the mapping
files.</li>
<li>Several changes to the Events API inside the ORM, to make sure many
possible extension scenarios work smoothly.</li>
<li>Enhancements to our Console Tools</li>
<li>Surpassed the 1000 unit-tests each running against Postgres, Mysql,
Sqlite and Oci8 drivers.</li>
<li>Moved from SVN to Git:
<a class="reference external" href="http://github.com/doctrine/doctrine2">http://github.com/doctrine/doctrine2</a></li>
</ul>
<p>We also did several painful backwards incompatible changes that seemed
necessary to clean up and optimize the API or allow the ORM to be even
faster than before. The beta phase beginning today will not contain any
larger BC breaks anymore, opening up this release for a broader testing
audience.</p>
<p>For the next iteration several enhancements are planned:</p>
<ul class="simple">
<li>Support for PDO IBM, IBM DB2, SqlSrv and PDO SqlSrv und MsSql drivers</li>
<li>Pessimistic Lock Support (FOR UPDATE and SHARED)</li>
<li>Support for Custom Hydration Modes</li>
<li>Support for Custom Persister Implementations</li>
<li>Support for handling very large collections of related objects
without needing an in-memory representation of the collection</li>
<li>Separation of Doctrine\Common, Doctrine\DBAL and Doctrine\ORM into
three different projects</li>
<li>Extend the documentation even further, adding quickstart tutorials,
cookbook recipes and enhancing the existing chapters.</li>
</ul>
<p>We also plan to support several extensions for the 2.0 release such as:</p>
<ul class="simple">
<li>Migrations</li>
<li>PHPUnit Database Testing Integration</li>
<li>NestedSet Support</li>
<li>Symfony 2 Support</li>
<li>Zend Framework 2 Support</li>
</ul>
<p>Please try out the new Beta release If you find the time and leave your
feedback in our <a class="reference external" href="http://www.doctrine-project.org/jira/secure/Dashboard.jspa">Issue
Tracker</a>,
the <a class="reference external" href="http://groups.google.com/group/doctrine-user">Mailing-List</a> or
come discuss with us on Doctrine 2 on Freenode #doctrine-dev.</p>
</div>]]></description>
            <pubDate>Tue, 27 Apr 2010 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/04/18/new-netbeans-php-codesniffer-plugin-version.html</link>
            <guid>http://www.whitewashing.de/2010/04/18/new-netbeans-php-codesniffer-plugin-version.html</guid>
            <title><![CDATA[New Netbeans PHP CodeSniffer Plugin Version]]></title>
            <description><![CDATA[<div class="section" id="new-netbeans-php-codesniffer-plugin-version">
<h1>New Netbeans PHP CodeSniffer Plugin Version</h1>
<p>This morning I took the time to merge several changes by <a class="reference external" href="http://manuel-pichler.de/">Manuel
Piechler</a> into <a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements">my Github
branch</a> of the
CodeSniffer Plugin and released a new NBM file for you to
<a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements/downloads">download</a>.
Here are the changes done by Manuel:</p>
<ul class="simple">
<li>Ability to specify the path to CodeSniffer Binary</li>
<li>Automatic Detection of all the installed Coding Standards</li>
<li>Fixed Automatic Binary Detection on Windows</li>
</ul>
<p>The only open TODO for this project is the possibility to specify
different standards on a per project basis, currently you can only
choose a global standard.</p>
</div>]]></description>
            <pubDate>Sun, 18 Apr 2010 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/12/18/generate-proxy-code-using-a-stream-wrapper.html</link>
            <guid>http://www.whitewashing.de/2010/12/18/generate-proxy-code-using-a-stream-wrapper.html</guid>
            <title><![CDATA[Generate Proxy code using a stream wrapper]]></title>
            <description><![CDATA[<div class="section" id="generate-proxy-code-using-a-stream-wrapper">
<h1>Generate Proxy code using a stream wrapper</h1>
<p>This blog-post is about an experiment and I am curios what others have to say about it. For Doctrine 2 we need to generate Proxy classes for the mapped objects to implement the Lazy Loading pattern. This is currently done with a console command or during runtime (for development). For Doctrine 2.1 we were thinking about using eval() as a third option for shared hosting or development environments. One annoyance of having to generate proxy code is that you have to regenerate it every time you change the original file. Additionally this makes deployment a little more complicated.</p>
<p>Today I got the idea to use stream wrappers to solve this problem. You can use stream-wrappers in combination with include/require and if you are using APC the generated php code can even be cached. That means you only have to generate the code once and after that everything is served from APCs opcode cache. Additionally by using the return values of <tt class="docutils literal"><span class="pre">stat()</span></tt> for the original file you can automatically regenerate your proxy code in APC when the original file changes.</p>
<p>I haven’t found a good way to pass state into a stream wrapper, that is why I put the data into $GLOBALS before calling <tt class="docutils literal"><span class="pre">include()</span></tt>. The client code looks like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="nx">stream_wrapper_register</span><span class="p">(</span><span class="s2">&quot;dc2proxy&quot;</span><span class="p">,</span> <span class="s2">&quot;Doctrine\ORM\Proxy\ProxyStreamWrapper&quot;</span><span class="p">);</span>

<span class="nv">$proxyDir</span> <span class="o">=</span> <span class="s2">&quot;dc2proxy:///proxies&quot;</span><span class="p">;</span>
<span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_EM'</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$em</span><span class="p">;</span>
<span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_ENTITYNAME'</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$className</span><span class="p">;</span>
<span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_PROXYCLASS'</span><span class="p">]</span> <span class="o">=</span> <span class="nv">$proxyClass</span><span class="p">;</span>

<span class="k">require</span> <span class="nv">$proxyDir</span><span class="o">.</span> <span class="s2">&quot;/&quot;</span><span class="o">.</span><span class="nb">str_replace</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="nv">$proxyClass</span><span class="p">)</span> <span class="o">.</span> <span class="s2">&quot;.php&quot;</span><span class="p">;</span>

<span class="nb">unset</span><span class="p">(</span><span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_EM'</span><span class="p">],</span> <span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_ENTITYNAME'</span><span class="p">],</span> <span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_PROXYCLASS'</span><span class="p">]);</span>
</pre></div>
</div>
<p>Not the nicest code, but it works. I can generate PHP code and have APC cache it for me until the original code changes.
The stream wrapper to make this work looks like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">namespace</span> <span class="nx">Doctrine\ORM\Proxy</span><span class="p">;</span>

<span class="k">class</span> <span class="nc">ProxyStreamWrapper</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="nv">$proxyCode</span><span class="p">;</span>

    <span class="k">function</span> <span class="nf">stream_open</span><span class="p">(</span><span class="nv">$path</span><span class="p">,</span> <span class="nv">$mode</span><span class="p">,</span> <span class="nv">$options</span><span class="p">,</span> <span class="o">&amp;</span><span class="nv">$opened_path</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span> <span class="o">=</span> <span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_EM'</span><span class="p">]</span>
                <span class="o">-&gt;</span><span class="na">getProxyFactory</span><span class="p">()</span>
                <span class="o">-&gt;</span><span class="na">getProxyClassCode</span><span class="p">(</span><span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_ENTITYNAME'</span><span class="p">],</span> <span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_PROXYCLASS'</span><span class="p">]);</span>

        <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">stream_stat</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$reflClass</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\ReflectionClass</span><span class="p">(</span><span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_ENTITYNAME'</span><span class="p">]);</span>
        <span class="nv">$stat</span> <span class="o">=</span> <span class="nb">stat</span><span class="p">(</span><span class="nv">$reflClass</span><span class="o">-&gt;</span><span class="na">getFileName</span><span class="p">());</span>
        <span class="nv">$stat</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="nv">$stat</span><span class="p">[</span><span class="s2">&quot;ino&quot;</span><span class="p">]</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="k">return</span> <span class="nv">$stat</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">url_stat</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="nv">$reflClass</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">\ReflectionClass</span><span class="p">(</span><span class="nv">$GLOBALS</span><span class="p">[</span><span class="s1">'DOCTRINE2_PSW_ENTITYNAME'</span><span class="p">]);</span>
        <span class="nv">$stat</span> <span class="o">=</span> <span class="nb">stat</span><span class="p">(</span><span class="nv">$reflClass</span><span class="o">-&gt;</span><span class="na">getFileName</span><span class="p">());</span>
        <span class="nv">$stat</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="nv">$stat</span><span class="p">[</span><span class="s2">&quot;ino&quot;</span><span class="p">]</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="k">return</span> <span class="nv">$stat</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">function</span> <span class="nf">stream_read</span><span class="p">(</span><span class="nv">$count</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$ret</span> <span class="o">=</span> <span class="nx">substr</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span><span class="p">,</span> <span class="nv">$count</span><span class="p">);</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">+=</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$ret</span><span class="p">);</span>
        <span class="k">return</span> <span class="nv">$ret</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">function</span> <span class="nf">stream_write</span><span class="p">(</span><span class="nv">$data</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="nv">$left</span> <span class="o">=</span> <span class="nx">substr</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span><span class="p">);</span>
        <span class="nv">$right</span> <span class="o">=</span> <span class="nx">substr</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">+</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$data</span><span class="p">));</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span> <span class="o">=</span> <span class="nv">$left</span> <span class="o">.</span> <span class="nv">$data</span> <span class="o">.</span> <span class="nv">$right</span><span class="p">;</span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">+=</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$data</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">function</span> <span class="nf">stream_tell</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">function</span> <span class="nf">stream_eof</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">&gt;=</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">function</span> <span class="nf">stream_seek</span><span class="p">(</span><span class="nv">$offset</span><span class="p">,</span> <span class="nv">$whence</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">switch</span> <span class="p">(</span><span class="nv">$whence</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">case</span> <span class="nx">SEEK_SET</span><span class="o">:</span>
                <span class="k">if</span> <span class="p">(</span><span class="nv">$offset</span> <span class="o">&lt;</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="nv">$offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
                     <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">=</span> <span class="nv">$offset</span><span class="p">;</span>
                     <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
                <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                     <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">break</span><span class="p">;</span>

            <span class="k">case</span> <span class="nx">SEEK_CUR</span><span class="o">:</span>
                <span class="k">if</span> <span class="p">(</span><span class="nv">$offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
                     <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">+=</span> <span class="nv">$offset</span><span class="p">;</span>
                     <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
                <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                     <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">break</span><span class="p">;</span>

            <span class="k">case</span> <span class="nx">SEEK_END</span><span class="o">:</span>
                <span class="k">if</span> <span class="p">(</span><span class="nb">strlen</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">)</span> <span class="o">+</span> <span class="nv">$offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
                     <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">position</span> <span class="o">=</span> <span class="nb">strlen</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">proxyCode</span><span class="p">)</span> <span class="o">+</span> <span class="nv">$offset</span><span class="p">;</span>
                     <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
                <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                     <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">break</span><span class="p">;</span>

            <span class="k">default</span><span class="o">:</span>
                <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>What do you think about this approach? Are there any potential problems I am not seeing?</p>
</div>]]></description>
            <pubDate>Sat, 18 Dec 2010 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2010/12/07/blog-refactorings-with-symfony2-doctrine-2-and-zeta-components.html</link>
            <guid>http://www.whitewashing.de/2010/12/07/blog-refactorings-with-symfony2-doctrine-2-and-zeta-components.html</guid>
            <title><![CDATA[Blog Refactorings with Symfony2, Doctrine 2 and Zeta Components]]></title>
            <description><![CDATA[<div class="section" id="blog-refactorings-with-symfony2-doctrine-2-and-zeta-components">
<h1>Blog Refactorings with Symfony2, Doctrine 2 and Zeta Components</h1>
<p>I have been playing around with <a class="reference external" href="http://www.symfony-reloaded.org">Symfony 2</a> quite a lot lately and have rewritten this blog using Symfony 2, <a class="reference external" href="http://www.doctrine-project.org">Doctrine 2</a> and Zeta Components. You can go over to Github and <a class="reference external" href="https://github.com/beberlei/Whitewashing">find its project page</a>.</p>
<p>Since I have found <a class="reference external" href="http://sphinx.pocoo.org/index.html">Sphinx</a> I am pretty impressed with Restructured Text and have now integrated that as writing language into my backend. Using <a class="reference external" href="http://zetacomponents.org/">Zeta Components</a> excellent Document component I transform the written ReST to XHTML. I <a class="reference external" href="https://github.com/beberlei/Whitewashing/tree/master/Util/DocumentVisitor">hooked into the Document rendering</a> and it now supports using the Sphinx directive ”.. code-block:: &lt;language&gt;” and runs the subsequent code through Geshi for highlighting. For example:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span>
<span class="k">echo</span> <span class="s2">&quot;hello world with ReST and Zeta Components!&quot;</span><span class="p">;</span>
</pre></div>
</div>
<p>Using <a class="reference external" href="http://teddevito.com/demos/textarea.html">the jQuery Plugin Tabby</a> and <a class="reference external" href="http://markitup.jaysalvat.com/home/">MarkitUp with a ReST extension</a> I can also write more conveniently now. Also to battle spam I have moved the comment system to Disqus.</p>
<p>My next plans for the blog bundle are:</p>
<ul class="simple">
<li>WebDav support for authoring. All articles will be named “slug.inputformat”, for example “blog-refactorings-with-symfony2-doctrine2-zetacomponents.rst”. For this I plan to write a custom backend for ezcWebdav.</li>
<li>Making the Bundle simpler to re-use by others.</li>
<li>More jQuery love to the backend.</li>
<li>Trigger some events in the blog post cycle and hook a twitter + facebook notification for new posts in there.</li>
</ul>
<p>Btw: This blog post is really just a bad excuse for me to test the ReST Editor in the backend. I hope you still enjoyed it ;)</p>
</div>]]></description>
            <pubDate>Tue, 07 Dec 2010 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/02/25/git-is-great-helping-out-with-mutateme.html</link>
            <guid>http://www.whitewashing.de/2009/02/25/git-is-great-helping-out-with-mutateme.html</guid>
            <title><![CDATA[Git is great: Helping out with MutateMe]]></title>
            <description><![CDATA[<div class="section" id="git-is-great-helping-out-with-mutateme">
<h1>Git is great: Helping out with MutateMe</h1>
<p>These last days I had fun with <a class="reference external" href="https://github.com/padraic/mutateme/tree">Padraic Bradys
MutateMe</a> project. It
dynamically changes your code (using PECL Runkit extension) and checks
weather your test cases fetch the errors occurring from changing the
source code. This is a great addition to having a test suite, because it
finds all the problematic test cases, that try to do too much and fail
to cover the code correctly.</p>
<p>I have also contributed to the MutateMe project already and this was
only possible due to Git and <a class="reference external" href="http://www.github.com">GitHub</a>, which
makes contributing to any project easy like writing a hello world
example in a random programing language. As such I have to agree with
Padraic: <a class="reference external" href="http://blog.astrumfutura.com/archives/390-Mutation-Testing-MutateMe-0.2.0alpha-Released.html">I love Git,
too!</a>
He already integrated my and <a class="reference external" href="http://www.phpunit.de">Sebastians</a>
changes back into the master and we didn’t have to focus on merging,
communication and integration a lot.</p>
<p>My <a class="reference external" href="http://github.com/beberlei/puma/tree/master">PUMA project</a> is also
hosted on GitHub (although nobody has looked into that yet), but I am
beginning to write a complete Runner now that calls all three components
<a class="reference external" href="http://www.phpunit.de">PHPUnit</a>, <a class="reference external" href="http://www.pdepend.org">PDepend</a>
and CodeSniffer at once and directly processes the results. When this is
done, I will pack it all up as a PEAR package for anyone to test out.</p>
</div>]]></description>
            <pubDate>Wed, 25 Feb 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/02/08/unittest-and-metrics-aggregator-tool-for-php.html</link>
            <guid>http://www.whitewashing.de/2009/02/08/unittest-and-metrics-aggregator-tool-for-php.html</guid>
            <title><![CDATA[Unittest and Metrics Aggregator Tool for PHP]]></title>
            <description><![CDATA[<div class="section" id="unittest-and-metrics-aggregator-tool-for-php">
<h1>Unittest and Metrics Aggregator Tool for PHP</h1>
<p>Both <a class="reference external" href="http://www.phpunit.de">PHPUnit</a> and
<a class="reference external" href="http:/www.pdepend.org">PDepend</a> offer export functionality in XML or
in a Test-database that is not quite readable for any user from the
start. Over the last month I have gradually written <a class="reference external" href="http://wiki.github.com/beberlei/puma">a nice webbased
tool</a>, that aggregates this data
and (todo in the future) relates them to help me with my open source
projects.</p>
<p>PHPUnit can be used with a <strong>–test-db-dsn</strong> command, which saves all
information about tests into a Database and PDepend has a strong Package
centric source parser for all sorts of project metrics.</p>
<p>What I needed for my <a class="reference external" href="http://framework.zend.com">Zend Framework</a>
related work (and other projects) was a tool that does a run of the
complete test-suite for me and saves the information, so that I can see
where problems occur (and if they are due to my changes or other
peoples). Since PHPUnit will stopped calculating additional metrics, I
have also integrated the fabulous PDepend Tool into this aggregator. It
shows me, what classes and functions need refactoring due to complexity
issues and draws some nice graphs that summarize all sorts of project
related information on a per package basis.</p>
<p>You can <a class="reference external" href="http://wiki.github.com/beberlei/puma">download or clone the an alpha version at
Github</a>. Its written with
<a class="reference external" href="http://www.ezcomponents.org">ezcMvcTools</a>, so you need this to work
too. A list of <a class="reference external" href="http://wiki.github.com/beberlei/puma">some screenshots is at the Github Wiki
page</a>.</p>
</div>]]></description>
            <pubDate>Sun, 08 Feb 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/02/13/update-on-unittest-and-metrics-tool.html</link>
            <guid>http://www.whitewashing.de/2009/02/13/update-on-unittest-and-metrics-tool.html</guid>
            <title><![CDATA[Update on Unittest and Metrics Tool]]></title>
            <description><![CDATA[<div class="section" id="update-on-unittest-and-metrics-tool">
<h1>Update on Unittest and Metrics Tool</h1>
<p>Some days ago i posted about the <a class="reference external" href="http://github.com/beberlei/puma/tree/master">PHP Unittest and Metrics
Aggregator</a> tool that i
have written on (and which I have dubbed PUMA). Discussing it with
people I came to the conclusion that the approach using
<a class="reference external" href="http://ezcomponents.org">ezcMvcTools</a> is quite problematic that it
forces to use this application, although the reporting and the
application are quite separate. This is not against ezcMvcTools: I love
it, its just the wrong type of support.</p>
<p>I began to split up the aggregator into some sort of importing-exporting
tool. You can specify library-, test- and output-directory of your
application and it will use the tools at hand
(<a class="reference external" href="http://www.phpunit.de">PHPUnit</a>, <a class="reference external" href="http://www.pdepend.org">PDepend</a>
and CodeSniffer currently) to generate their XML formatted reports. It
then parses those XML outputted files and combines their result to give
a consistent view on your application.</p>
<p>The Import-To-Output generator uses a three-step approach. An importer
emits signals to report observers, which will then hand over their
collected data to specific html pages that are then generated to the
disc. This is a very flexible approach that allows anyone to extend and
re-use the tool to generate project metrics, unittest overview and other
interesting details on your application.</p>
<p><a class="reference external" href="http://github.com/beberlei/puma/tree/master">Have a look at the tool on
Github</a> and play with it.
I would really like to hear your thoughts.</p>
</div>]]></description>
            <pubDate>Fri, 13 Feb 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/05/01/explicit-code-requires-no-comments-only-bad-code-does.html</link>
            <guid>http://www.whitewashing.de/2009/05/01/explicit-code-requires-no-comments-only-bad-code-does.html</guid>
            <title><![CDATA[Explicit Code requires no comments - Only bad code does]]></title>
            <description><![CDATA[<div class="section" id="explicit-code-requires-no-comments-only-bad-code-does">
<h1>Explicit Code requires no comments - Only bad code does</h1>
<p>Following the recent discussion on commenting source code by <a class="reference external" href="http://www.brandonsavage.net/on-code-commenting-and-technical-debt/">Brandon
Savage</a>
and <a class="reference external" href="http://mtabini.blogspot.com/2009/04/myth-of-myth-of-self-commenting-code.html">Marco
Tabini</a>,
I wanted to add upon Marcos code example to show that it not even needs
any inline comments and can be greatly enhanced in readability with
taking 2-5 minutes of time and refactoring the code. The original code
sample was:</p>
<blockquote>
<div><div class="highlight-python"><pre>function __construct(array $pathInfo) {
    $section = $pathInfo[0];
    $file = $pathInfo[1];

    // Assume that the location of this file is inside the main trunk, and that pathInfo has already been filtered.

    $path = dirname(__FILE__) . '/../../' . $section . '/xml/static/' . $file . '.xml';

    if (!file_exists($path)) {
        Controller::singleton()-&gt;doError(404);
    }

    parent::__construct('main/xsl/template.xsl', $path);
}</pre>
</div>
</div></blockquote>
<p>This sample is somehow related to the response and view rendering of an
application and its pretty understandable. For me there are some squirks
though that would make me have to scroll to other classes to see how
they interact. For example the path information falls from heaven. Why
is it an array of 2 values and are these sections set the same all the
time? And what exactly happens when the front controller does the 404
error? Is there a die() or exit in the <strong>doError()</strong></p>
<p>The Agile movement postulates the phase of refactoring for a finished
piece of code. Rebuilding the hacked solutions that did it to make them
more understandable. I applied this to Marcos code snippet. The
refactoring produces about double the code, but its done entirely by
using NetBeans nice Rename variable and copy paste on extracting
methods, which takes not more than 5 minutes.</p>
<blockquote>
<div><div class="highlight-python"><pre>class StaticXmlXsltRendererImpl extends AbstractXsltView
{
    function render(array $filteredPathInfo) {
        $templateValuesXmlPath = $this-&gt;getTemplateValuesXmlFile($filteredPathInfo);

        if(!$this-&gt;templateExists($templateValuesXmlPath)) {
            Controller::singleton()-&gt;doError(404);
        } else {
            parent::render('main/xsl/template.xsl', $templateValuesXmlPath);
        }
    }

    private function getTemplateValuesXmlFile($filteredPathInfo) {
        $section = $this-&gt;getSection($filteredPathInfo);
        $file = $this-&gt;getFile($filteredPathInfo);

        // Assume that the location of this file is inside the main trunk
        return dirname(__FILE__) . '/../../' . $section . '/xml/static/' . $file . '.xml';
    }


    private function getSection($pathInfo) {
        return $pathInfo[0];
    }

    private function getFile($pathInfo) {
        return $pathInfo[1];
    }

    private function templateExists($path) {
        return file_exists($path);
    }
}</pre>
</div>
</div></blockquote>
<p>In this code snippet the class name, variable names and methods clearly
communicate what is done, which wasn’t the case in the previous example.
The only change for the clients is the change of using the constructor
to using the <strong>render()</strong> method, which communicates the intend more.
Also the render method now clearly communicates that either the error or
the parent rendering is executed and leaves no doubt about it.</p>
<p>The <strong>getTemplateValuesXmlFile()</strong> method still uses the comment to show
the assumption about relative paths, but this is only the case because
application configuration is made implicit into the code. This has to be
extracted to be an explicit configuration constant and the comment can
go.</p>
<blockquote>
<div><div class="highlight-python"><pre>private function getTemplateValuesXmlFile($filteredPathInfo) {
    $section = $this-&gt;getSection($filteredPathInfo);
    $file = $this-&gt;getFile($filteredPathInfo);

    return APPLICATION_ROOT . '/' . $section . '/xml/static/' . $file . '.xml';
}</pre>
</div>
<p>In my opinion commenting code is necessary only for non-refactored
code that has been hacked into existence and is hard to understand.
Either the programmer has to get it done and has no chance to
clearly communicate the intend. Or what is even worse the to be
changed legacy code is hard to understand but you can’t take the
chances to refactor it because its also already in production and
has no tests. Now from the second point it is obvious that upon ugly
code you put only more and more ugly code to fix the problems. This
is what leads to the legacy maintenance problems that pretty much
every programmer faces. And then commenting comes into play: You
have to add a new feature X and it has to be done fast. You don’t
really understand the code or how it works together but you know you
can put the new code for the feature into existence but its really
unintuitive. So you begin to comment it excessively, because its the
only way to clearly show its intend.</p>
<p>There are two mindestting factors that help to write code that is
understandable without having to excessively comment it:</p>
<ul class="simple">
<li>From the beginning, do not write code for the computer but for
developers. Changing this attitude really helps to write
understandable code like the one above.</li>
<li>Only leave code better than it was before, never worse.</li>
</ul>
<p>There are five technical practices that - when followed - allow to
write clearly communicating code from the beginning:</p>
<ol class="arabic simple">
<li>Giving classes, variables and methods good names. This is a
no-brainer but few people seem to follow it anyways.</li>
<li>Following the object-oriented <strong>Single Responsibility Principle</strong>
by never giving a class more than one responsibility. Macros
example seems to follow this one.</li>
<li>Methods should never switch in the level of detail. Micro-work at
the datastructure level should never be mixed with macro level
delegation to executing large chunks of code. Macros code
violates this by mixing the path building micro-level work with
the macro-level work of rendering the XSLT template. The path
building code can be hidden behind a method to communicate intend
more clearly.</li>
<li>Exchange if conditions with private methods that explain the
condition being checked for. In Marcos example this is not really
necessary, because file_exists already is quite a good
description to the condition. But in cases of logical
combinations of conditions the method extracting is a superior
way to explain the conditions intend without having to write a
comment.</li>
<li><strong>Seperate Query and Command</strong>: A method never should do a query
which returns the state of an object and a command which executes
a set of rules on the state.</li>
</ol>
<p>These practices sum up to one guideline: Make code explicit. This
obviously requires less commenting since a comment of explicit code
would be duplication and duplication is bad. What if you have a
project that does not follow this guidelines? Then of course
comments should be used to explain code, but in the long run this
should be refactored to self-explaining code. Additionally every new
feature should be programmed explicitly to follow the “leave code
better than before” principle.</p>
<p>In my opinion two refactoring tools are missing that would greatly
help PHP programmers write nice to read code: Extract method and
Replace magic value with constant. Can someone integrate them into
NetBeans please?</p>
<p><strong>Update:</strong> Fixed a creepy copy-paste code bug, thanks to azeroth
for pointing out. Moved methods around a bit to be more reading
friendly.</p>
</div></blockquote>
</div>]]></description>
            <pubDate>Fri, 01 May 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/06/16/using-a-dependency-injection-container-with-zend-application.html</link>
            <guid>http://www.whitewashing.de/2009/06/16/using-a-dependency-injection-container-with-zend-application.html</guid>
            <title><![CDATA[Using a Dependency Injection Container with Zend_Application]]></title>
            <description><![CDATA[<div class="section" id="using-a-dependency-injection-container-with-zend-application">
<h1>Using a Dependency Injection Container with Zend_Application</h1>
<p>Much has been written on Dependency Injection lately, mostly by Padraic
Brady
(<a class="reference external" href="http://blog.astrumfutura.com/archives/394-The-Case-For-Dependency-Injection-Part-1.html">1</a>,
<a class="reference external" href="http://blog.astrumfutura.com/archives/395-The-Case-For-Dependency-Injection-Part-2.html">2</a>)
and Fabien Potencier
(<a class="reference external" href="http://fabien.potencier.org/article/11/what-is-dependency-injection">1</a>,
<a class="reference external" href="http://fabien.potencier.org/article/12/do-you-need-a-dependency-injection-container">2</a>,
<a class="reference external" href="http://fabien.potencier.org/article/13/introduction-to-the-symfony-service-container">3</a>,
<a class="reference external" href="http://fabien.potencier.org/article/14/symfony-service-container-using-a-builder-to-create-services">4</a>,
<a class="reference external" href="http://github.com/fabpot/Pimple/tree/master">5</a>). My subjective
feeling tells me there are now more PHP DI containers out there than CMS
or ORMs implemented in PHP, including two written by myself (an
<a class="reference external" href="http://www.beberlei.de/sphicy/">overengineered</a> and <a class="reference external" href="http://github.com/beberlei/yadif/tree/master">a useful
one</a>). Its an awesome
pattern if used on a larger scale and can (re-) wire a complex business
application according to a clients needs without having to change much
of the domain code. It aims at a complete separation of object
instantiation and dependency tracking from the business logic.</p>
<p>Beginning with version 1.8 Zend Framework is able to integrate any of
these DI containers into its <strong>Zend_Application</strong> component easily. The
Application component initializes a set of common resources and pushes
them into the MVC stack as additional Front Controller parameters.
Technically a <strong>Zend_Registry</strong> instance holds all these resources with
their respective resource names as keys. The resources are accessible
inside the Front Controller and the Action Controller classes. Assume
the resource ‘Db’ is initialized in your application, you can access it
with:</p>
<blockquote>
<div><div class="highlight-python"><pre>$front = Zend_Controller_Front::getInstance();
$container = $front-&gt;getParam('bootstrap')-&gt;getContainer();
$db = $container-&gt;db;

// or:
class FooController extends Zend_Controller_Action {
    public function barAction()
    {
        $container = $this-&gt;getInvokeArg('bootstrap')-&gt;getContainer();
        $db = $container-&gt;db;
    }
}</pre>
</div>
</div></blockquote>
<p>This is pretty much dependency injection already, but the default
registry approach suffers from two serious problem: New instances can
only be added to the Container by implementing new Zend_Application
resources and these instances cannot be lazy loaded. All resources used
by Zend_Application are always loaded on every request. But the
application container implementation was developed with Dependency
Injection in mind and is not tied to the use of Zend_Registry. Only
three magic methods are required by any container that wants to be
Zend_Application compliant: __get(), __set() and __isset(). Each
instantiated resource is pushed via __set() into the container. If
required by another resource, __isset() is used to check whether a
resource with the given name exists inside the container and __get()
is used to retrieve the instances from the container.</p>
<p>Some month ago I extended
<a class="reference external" href="http://github.com/beberlei/yadif/tree/master">Yadif</a>, a lightweight
PicoContainer-like DI container for PHP written by Thomas McKelvey, with
several features that make it a very powerful DI container in my
opinion. It has a detailed documentation and examples on the GitHub Page
if you want to check it out. I extended Yadif to be Zend_Application
compliant in a way that the application-wide Zend_Application resources
can be used as dependencies for objects that are lazy-loaded from the
container. Skipping the tech-talk, here is an example. First we have to
replace the default Container with Yadif:</p>
<blockquote>
<div><div class="highlight-python"><pre>$objects = new Zend_Config_Xml(APPLICATION_PATH.&quot;/config/objects.xml&quot;);
$container = new Yadif_Container($objects);

$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/config/application.xml'
);
// Set Yadif as Container
$application-&gt;getBootstrap()-&gt;setContainer($container);
$application-&gt;bootstrap()
            -&gt;run();</pre>
</div>
</div></blockquote>
<p>Assume you run Zend_Application with a “Db” and a “Cache” resource.
These resources are loaded on every request. The objects configured in
Yadif however are not instantiated until they are requested for the
first time from the container. We can merge these two worlds and make
use of the Application resources inside the Yadif Configuration
“objects.xml”, which looks like:</p>
<blockquote>
<div><div class="highlight-python"><pre>&lt;?xml version=&quot;1.0&quot; ?&gt;
&lt;objects&gt;
    &lt;myModel&gt;
        &lt;class&gt;MyModel&lt;/class&gt;
        &lt;arguments arg1=&quot;db&quot; arg2=&quot;cache&quot; /&gt;
    &lt;/myModel&gt;
&lt;/objects&gt;</pre>
</div>
<p>Instantiating a <strong>myModel</strong> class inside the Action Controller uses
the the Database and Cache resources as constructor arguments:</p>
<blockquote>
<div><div class="highlight-python"><pre>class FooController extends Zend_Controller_Action {
    public function barAction()
    {
        $container = $this-&gt;getInvokeArg('bootstrap')-&gt;getContainer();
        $myModel = $container-&gt;myModel;
    }
}</pre>
</div>
</div></blockquote>
<p>Given the possibilites by the Yadif_Container you are now empowered
to use Dependency Injection for all your application objects and
make use of Zend_Applications resource system. Furthermore any
other dependency injection container, simple or complex, can also be
integrated easily.</p>
</div></blockquote>
</div>]]></description>
            <pubDate>Tue, 16 Jun 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/11/14/netbeans-php-codesniffer-plugin-now-with-options-dialog.html</link>
            <guid>http://www.whitewashing.de/2009/11/14/netbeans-php-codesniffer-plugin-now-with-options-dialog.html</guid>
            <title><![CDATA[Netbeans PHP CodeSniffer Plugin: Now with Options Dialog]]></title>
            <description><![CDATA[<div class="section" id="netbeans-php-codesniffer-plugin-now-with-options-dialog">
<h1>Netbeans PHP CodeSniffer Plugin: Now with Options Dialog</h1>
<p>Just two days before the <a class="reference external" href="http://www.phpconference.de">International PHP Conference
09</a> will start I got an email from
<a class="reference external" href="http://github.com/alexandrehaguiar">alexandrehaguiar</a> that he forked
my Netbeans PHP CodeSniffer plugin and added the long awaited Options
screen. This is just awesome! This way I don’t have to ask the Netbeans
guys at IPC all the questions about how to implement it. I merged the
changes back into my branch and released a new version which also fixed
another small bug. For me it works with both Netbeans 6.7.1 and 6.8
Beta. I want to thank alexandre very much for this awesome contribution.</p>
<p>What you can do now is chose the Coding Standard you want to use in an
Options Dialog under the “Miscellaneous” button. You can choose from a
list of pre-defined standards, or even enter your own if you use one.
Additionally you can disable that warning are shown, so that with any
given coding standard you only see the errors.</p>
<p><a class="reference external" href="http://cloud.github.com/downloads/beberlei/netbeans-php-enhancements/phpcsoptions.png">|image0|</a></p>
<p>You can download the new version from the <a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements/downloads/">Github Project Downloads
page</a>.</p>
</div>]]></description>
            <pubDate>Sat, 14 Nov 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/08/31/enums-in-php.html</link>
            <guid>http://www.whitewashing.de/2009/08/31/enums-in-php.html</guid>
            <title><![CDATA[Enums in PHP]]></title>
            <description><![CDATA[<div class="section" id="enums-in-php">
<h1>Enums in PHP</h1>
<p><a class="reference external" href="http://blog.tobias-olry.de">A colleague of mine</a> complained about the
missing support for Enums in PHP and how one often wants to have a
variable that is constant and has one of several specific values. We
came up with an elegant solution that we want to share, maybe its even
helpful to you.
If you want to implement Enum behaviour with a simple string or int
value you end up with having to validate the values at several different
locations in the code rather than being able to strictly enforce the
Enum structure by using typehints.</p>
<p>We discussed several approaches to this problem that all seemed a bit
ugly in one or another way. For example the <strong>SplEnum</strong> class is a step
in the right direction, however you can only use a type hint for
“SplEnum” or add another inheritance layer. Also you have to implement
different classes for each enum type, which requires you to implement a
factory method for your enum to help with creation of the different
types.</p>
<p>We came up with a very simple Enum concept. It uses reflection in the
constructor to check if the given value is a valid Enum value by
checking it against all the defined constants of the implementing class
and throws an Exception if it is not. The __toString() magic method is
implemented to allow for simple checks of the enums value. Strict
type-checks are not possible with this construct, however in our opinion
it is a very elegant solution to enforce a limited set of specific
values throughout your code-base.</p>
<p>Here is the code plus a small example:</p>
<blockquote>
<div><div class="highlight-python"><pre>abstract class MyEnum
{
    final public function __construct($value)
    {
        $c = new ReflectionClass($this);
        if(!in_array($value, $c-&gt;getConstants())) {
            throw IllegalArgumentException();
        }
        $this-&gt;value = $value;
    }

    final public function __toString()
    {
        return $this-&gt;value;
    }
}

class Foo extends MyEnum
{
    const FOO = &quot;foo&quot;;
    const BAR = &quot;bar&quot;;
}

$a = new Foo(Foo::FOO);
$b = new Foo(Foo::BAR);
$c = new Foo(Foo::BAR);

if($a == Foo::FOO) {
    echo &quot;My value is Foo::FOO\n&quot;;
} else {
    echo &quot;I dont match!\n&quot;;
}

if($a == $b) {
    echo &quot;a value equals b value!\n&quot;;
}
if($b == $c) {
    echo &quot;b value equals c value!\n&quot;;
}</pre>
</div>
</div></blockquote>
<p>Now you could nice things such as:</p>
<blockquote>
<div><div class="highlight-python"><pre>function doStuff(Foo $foo) {
    switch($foo) {
        case Foo::FOO:
            echo &quot;do more here!\n&quot;;
            break;
        case Foo::BAR;
            echo &quot;evil stop!\n&quot;;
            break;
    }
}

doStuff($a);</pre>
</div>
</div></blockquote>
<p>What are your thoughts?</p>
</div>]]></description>
            <pubDate>Mon, 31 Aug 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/23/zend-form-and-the-model-yet-another-perspective-using-a-mediator.html</link>
            <guid>http://www.whitewashing.de/2009/01/23/zend-form-and-the-model-yet-another-perspective-using-a-mediator.html</guid>
            <title><![CDATA[Zend_Form and the Model: Yet another perspective using a Mediator]]></title>
            <description><![CDATA[<div class="section" id="zend-form-and-the-model-yet-another-perspective-using-a-mediator">
<h1>Zend_Form and the Model: Yet another perspective using a Mediator</h1>
<p><a class="reference external" href="http://weierophinney.net/matthew/">Matthew Weier O’Phinney</a> of the
Zend Framework Devteam <a class="reference external" href="http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html">wrote a controversial post on integrating
Zend_Form and the Model last
month</a>.
He separated concerns of view and model that communicate via a Form, by
calling just thee validation functions on the Form inside the mode. On
request you could retrieve the model to the controller and view layers.
I already wrote into his comments that I didn’t like the solution
because it relies on implicit rules for the developers to use the Form
component correctly in all layers. Additionally the building of the form
using this approach would be performed inside the model, although
strictly speaking this is responsibility of the View Layer. Another
negative point is duplication of input filtering code that has to be
performed to use certain variables inside the controller or when
different forms talk with the same model.</p>
<p><a class="reference external" href="http://codeutopia.net">Jani</a> took it up and <a class="reference external" href="http://codeutopia.net/blog/2009/01/07/another-idea-for-using-models-with-forms/">proposed writing
validators for forms and attaching them to the
Form</a>
as sort of a mediator. I am not a fan of this approach either, because
the validator would have to include domain logic but is not really a
part of the domain logic anymore but just a validator. Developers might
forget using the validator inside the model for all their actions or
there would be duplication of code in some places. In a perfect world,
only functions of the models public interface should be called for
validation.</p>
<p>My personal favorite for Form and Model integration is a <strong>mediator</strong>
object between the two layers. Your model will have to include an
additional interface with one function <strong>acceptFormRequest($values);</strong>
which accepts an array of validated Zend Form field values. It then
tries to apply the validated data into a record. Additional required
validations of the model can take place in this function, which
separates the concerns of Form validation and Model data validation.
Still the mediator merges those differences together: You can throw an
Exception and it will be attached as a custom error message to the Form.
The following very short code will show the required interface and the
mediator code. This code is very simple and might produce maintenance
overhead fast, but I propose some refactoring enhancements later in the
discussion.</p>
<blockquote>
<div><div class="highlight-python"><pre>interface WW_Model_AcceptFormRequest
{
    /**
     * Acceept a form request
     * @param array $values
     * @return WW_Record_Interface
     */
    public function acceptFormRequest($values);
}
class WW_Model_FormMediator
{
    /**
     * Try to push the form request to the model
     *
     * @param Zend_Form $form
     * @param WW_Model_AcceptFormRequest $model
     * @return WW_Record_Interface
     */
    public function pushFormToModel(Zend_Form $form, WW_Model_AcceptFormRequest $model)
    {
        if(!$form-&gt;isValid()) {
            throw new Exception(&quot;Form not valid!&quot;);
        } else {
            $values = $form-&gt;getValues();
            try {
                $record = $model-&gt;acceptFormRequest($values);
            } catch(Exception $e) {
                // This exception message comes from the model, because validation failed
                $form-&gt;addErrorMessage($e-&gt;getMessage());
                throw new Exception(&quot;Form request not accepted by model!&quot;);
            }
        }
        return $record;
    }
}</pre>
</div>
</div></blockquote>
<p>You can see the mediator has two different stages where errors can
occur: When the form is not valid or the model is not valid. Both exits
can be catched inside the controller and are the indicator that the form
has to be displayed again for further input corrections. When successful
the model returns a valid record that applies to the form and model
requirements and can be displayed. If this record should be persistent
this would have been done inside the <strong>acceptFormRequest</strong> function
already. An example using a very simple Model using the a BankAccount
example. We have a form that validates all the incoming request data for
a withdrawal of money, though does not validate it against the models
internal state. Our BankAccountModel implements the
<strong>WW_Model_AcceptFormRequest</strong> interface and returns a valid
BankAccount. If found the given amount is withdrawn.</p>
<blockquote>
<div><div class="highlight-python"><pre>class BankAccountModel implements WW_Model_AcceptFormRequest {
    public function acceptFormRequest($values)
    {
        $bankAccount = $this-&gt;getBankAccountBy($values['bankAccountNumber'], $values['pin']);
        if($values['action'] == &quot;withdraw&quot;) {
            $bankAccount-&gt;withdraw($values['amount']);
            $this-&gt;save($bankAccount);
        } else {
            // unknown action...
        }
    }
    public function getBankAccountBy($key, $password) {
        // Find by Primary Key returning 'BankAccount' instance or exception if not found.
    }
    public function save(BankAccount $ba) {
        // Sql for saving the Bank Account
    }
}

class BankAccount
{
    public function withdraw($amount)
    {
        if( ($this-&gt;getBalance()-$amount) &lt; 0 ) {
            throw new Exception(&quot;You cannot withdraw more money than your bank account holds!&quot;);
        }
        $this-&gt;balance -= $amount;
    }
}</pre>
</div>
</div></blockquote>
<p>Two exceptions might be thrown in this case: The Bank Account number
does not exist or the password is wrong. Or you are not allowed to
withdraw the given amount of money. If any of those exceptions is thrown
the Model does not accept the form data and the form will have to be
displayed again for the client showing the new error message that was
returned from the model. The controller handling this process would look
like this:</p>
<blockquote>
<div><div class="highlight-python"><pre>class BankAccountController extends Zend_Controller_Action {
    public function performWithdrawlAction() {
        $form = new BankAccountWithdrawlForm(); // extends Zend_Form and builds the form

        if($this-&gt;getRequest()-&gt;isPost()) {
            $mediator         = new WW_Model_FormMediator();
            $bankAccountModel = new BankAccountModel();
            try {
                $bankAccount = $mediator-&gt;pushFormToModel($form, $bankAccountModel);

                $this-&gt;view-&gt;assign('bankAccount', $bankAccount); // Show new balance in view!
            } catch(Exception $e) {
                $this-&gt;view-&gt;assign('withdrawlForm', $form);
                $this-&gt;_redirect('showWithdrawl');
            }
        } else {
            $this-&gt;view-&gt;assign('withdrawlForm', $form);
            $this-&gt;_redirect('showWithdrawl');
        }
    }
}</pre>
</div>
</div></blockquote>
<p>You can see the mediator tightly integrates Form and Model without both
components knowing too much of each other. Still you can add error
messages received from the model into the Form and redisplay it. One
negative point of this approach is the fact that you only have one
method for accepting form data, which could result in variable checking
and redispatching in the case of many different operations that can be
performed on the same model. For this case you might want to either:</p>
<ol class="arabic simple">
<li>Rewrite the mediator to accept a specific model class (not the
interface) and call the required custom method that matches the forms
request. (Best approach for separation concerns)</li>
<li>Rewrite the mediator to also pass the <strong>get_class($form);</strong> value to
the model for decision making (Faster approach)</li>
</ol>
<p>There is still some overhead on using the mediator. Since its generic
you could build an Action Helper for it and use the direct call
mechanism to save some lines of code.</p>
</div>]]></description>
            <pubDate>Fri, 23 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/14/finally-zend-mail-charset-and-or-long-lines-header-encoding-bug-fixed.html</link>
            <guid>http://www.whitewashing.de/2009/01/14/finally-zend-mail-charset-and-or-long-lines-header-encoding-bug-fixed.html</guid>
            <title><![CDATA[Finally: Zend_Mail charset and/or long lines header encoding bug fixed]]></title>
            <description><![CDATA[<div class="section" id="finally-zend-mail-charset-and-or-long-lines-header-encoding-bug-fixed">
<h1>Finally: Zend_Mail charset and/or long lines header encoding bug fixed</h1>
<p>There was this <a class="reference external" href="http://framework.zend.com/issues/browse/ZF-1688">lurking bug in
Zend_Mail</a> which
destroyed every Mail-Header (and corresponding Mail) with non US-ASCII
Chars and more than an encoded length of 74 chars. This is quite a huge
subset of mails, but it seems a nice solution was not so easy, at least
nobody tried to fixed it for quite some time.</p>
<p>Where many hackish solutions we’re offered, Ota Mares aka Littlex spent
incredible time to hunt the original problem down and with his help I
tag-teamed the bug to death today. Saturo Yoshida of Zend Fame added
some further spice regarding an alternative solution with Base64
Encoding instead of Quoted Printable Mime Header encoding.</p>
<p>In the end the solution we chose was, not to re-use the Mime encoding
function that is specific to MIME bodies according to
<a class="reference external" href="http://tools.ietf.org/html/rfc2045">RFC2045</a>, but to write a
completely new algorithm for Mime Headers, whose rules are specified in
<a class="reference external" href="http://tools.ietf.org/html/rfc2047">RFC2047</a>. This is now done and
unit-tests prove its working according to standard.</p>
<p>What is missing now is people trying that fix on as many Mail platforms
as possible and <a class="reference external" href="http://framework.zend.com/issues/browse/ZF-1688">giving feedback in the
issue</a> if a lengthy
subject with non-ASCII chars is displayed correctly.</p>
</div>]]></description>
            <pubDate>Wed, 14 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/11/howto-file-a-good-bug-report-suggestions-for-framework-users.html</link>
            <guid>http://www.whitewashing.de/2009/01/11/howto-file-a-good-bug-report-suggestions-for-framework-users.html</guid>
            <title><![CDATA[Howto file a good bug report: Suggestions for framework users]]></title>
            <description><![CDATA[<div class="section" id="howto-file-a-good-bug-report-suggestions-for-framework-users">
<h1>Howto file a good bug report: Suggestions for framework users</h1>
<p>I have fixed quite a number of bugs for the ZF lately, which lead me to
this post about how to file a good bug report. There are many annoying
bug reports out there, where the reporter of the bug withholds important
information to the bugfixer unintended. This advice applies bug reports
in general of course.</p>
<p>What are the benefits of a good bug report? The bug generally gets fixed
faster, when the developer has more information at hand. Additionally
other developers might come to rescue since they can understand the
issue faster. These benefits are good for both parties. If you take no
time for a good bug report, your issue might risk to end up getting old
or closed unfixed.</p>
<ul class="simple">
<li><strong>Post the whole Exception Stack Trace</strong>: If the library throws an
Exception into your application that is unexpected and may indicate
an bug: Do not post the Message or Exception name only. The exception
may be thrown in many different places or due to different reasons.
The PHP exception class offers the method <strong>getTraceAsString()</strong>,
which offers many information to the developer what the cause of the
exception might be. Please use it!</li>
<li><strong>Post codefixes in a patch format</strong>: When you find a bug in the
framework, it is quite possible that you can offer a fix directly.
Writing “Replace x in line y with z” does not help very often. The
component might be in flux and the line positions change more often
than you think. Please create a diff file of this changes that
indicate the precise position of the change. This diff also includes
2 lines above and below the patched code for direction of the
developer. SVN Diffs are even more useful since they include the
revision where you fixed the bug in.</li>
<li><strong>Post reproducible cases as PHPUnit Test</strong>: If you find a bug and
can show how to reproduce it: Write a unittest to prove it. It is ZF
policy to create a unittest for each bugfix showing that the bug was
indeed fixed and previous functionality remains the same, so this
unit-test has to be written anyways. Many show-offs rely on massive
<strong>echo</strong> statements or <strong>var_dump</strong>, which render them almost
useless for the developer.</li>
<li><strong>Attach a unit-test to a submitted patch</strong>: This is related to the
previous point. If you add a unit test your patch will get more
attention. It will prove that you have thought about the patch, its
consequences and that you might have checked it does not break
backwards compatibility. This is worth a lot.</li>
<li><strong>Run the test suite with your patch</strong>: If you want to provide a
patch. Run the testsuite of the Zend Framework. It might break
expected behaviour. When you post a patch that will break BC, it will
be recognized. Your bug report might be closed, which helps nobody.</li>
</ul>
<p>When you find a bug you have probably thought about it and how to fix
it. This is valuable information. Disregarding one of this points will
lead to missing information on part of the developer that he has to
“learn” again. This takes time, which may make your bug last longer than
it should.</p>
</div>]]></description>
            <pubDate>Sun, 11 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/11/what-will-be-new-in-zf-1-8.html</link>
            <guid>http://www.whitewashing.de/2009/01/11/what-will-be-new-in-zf-1-8.html</guid>
            <title><![CDATA[What will be new in ZF 1.8]]></title>
            <description><![CDATA[<div class="section" id="what-will-be-new-in-zf-1-8">
<h1>What will be new in ZF 1.8</h1>
<p>In February or March 2009 the 1.8 version of the <a class="reference external" href="http://framework.zend.com">Zend
Framework</a> is scheduled to be released. I
have contributed some stuff already regarding ZendX_JQuery and
Zend_Soap.</p>
<p>Both components have seen numerous bugfixes and I managed to get the
JQuery helper down to zero open issues. I have also taken over the
<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Json_Expr+to+allow+Javascript+Expressions+(functions)+to+be+encoded+using+Zend_Json">Zend_Json_Expr
proposal</a>,
which will be a huge benefit to everything JSON that can be done with
ZF. Foremost it is an integral part for the jQuery component which
heavily relies on javascript callbacks.</p>
<p>The Soap Autodiscover and WSDL classes compatibility with Java and .NET
has been optimized due to great user feedback, as well as some bugfixes
to the newly added WSDL type detection strategies.</p>
<p>Additionally I went on another bug killing spree and fixed around 20-30
old bugs in a wide range of different components.</p>
</div>]]></description>
            <pubDate>Sun, 11 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/12/on-publishing-webservices-within-mvc-frameworks.html</link>
            <guid>http://www.whitewashing.de/2009/01/12/on-publishing-webservices-within-mvc-frameworks.html</guid>
            <title><![CDATA[On Publishing Webservices within MVC Frameworks]]></title>
            <description><![CDATA[<div class="section" id="on-publishing-webservices-within-mvc-frameworks">
<h1>On Publishing Webservices within MVC Frameworks</h1>
<p>Webservices are a very important part in today’s enterprise applications.
They tie applications of different age or programming languages together
or allow applications of different subcontracters to speak to each
other. Because they use HTTP, a stateless network protocol, considerable
overhead floods the pipes when you use them, which should be minimized.</p>
<p><a class="reference external" href="http://martinfowler.com">Martin Fowler</a> writes in his <a class="reference external" href="http://martinfowler.com/eaaCatalog/">PEAA
book</a>, that if you have the
option not to use distributed objects (which are implemented via
webservice) you should not distribute them. Considerable effort has to
be brought into keeping complex webservices performant.</p>
<p>Still people make mistakes about webservices all the time (me included
for example proposing a dispatcher for the ZF that could be used for
webservices).</p>
<p>When people report problems with the Zend Soap component they often post
a stripped down example that involes their webservice being instantiated
within a controller. This is a very bad decision based on different
arguments:</p>
<ul class="simple">
<li><strong>Dispatching overhead</strong>: Dispatching, Routing, Pre- and
Postfiltering is costly in all frameworks. You give up the
performance of having numerous PHP scripts that act as controller on
their own. You get centralized filtering, authentication and other
benefits. But those benefits generally do not aply to XML, JSON or
SOAP requests, because you cannot parse them or access their
properties. You give up the performance of a page controller for
webservices to gain mostly nothing.</li>
<li><strong>HTTP Request uselessness</strong>: Web frameworks work with HTTP request
objects. The request of webservices facilitates HTTP to act as a far
more complex request. No framework I know off, allows to work with
the webservice requests outside the Webservice handler. What a SOAP
or XML-RPC request does in your MVC is only get passed through
numerous costly stages that offer no benefit, before it hits the
target. Only the parsing of HTTP-Headers might offer additional
benefit, but the gain is low, since they are available to PHP scripts
at no cost.</li>
<li><strong>Webservices already seperate concerns</strong>: Take the PHP SOAPServer as
an example. It is an MVC application on its own, the controlling
aspect of the SOAPServer parses the SOAP Request and sends it to the
model, a class given by the user, which in turn works and returns the
result as an SOAP Response View. You have to decouple model and view
for a webservice handler otherwise it would generate invalid
responses. Why nest a perfectly separated operation into another one?
You gain no more of this additional separation, except performance
decrease.</li>
</ul>
<p>So what are good practices to implement webservices?</p>
<ul class="simple">
<li>Use a page controller that generates no MVC overhead. In context of
the Zend Framework: Add a new php script to your web root and add a
new route into your .htaccess file that redirectes the desired
location of the webservice to the script that overwrites the standard
catch-all incoming requests to the front controller script.</li>
<li>Use the proxy pattern and the invaluable __call() method to
implement wrapper objects for authentication and session management
of the webservice. These classes can easily be reused by all
webservice page controllers of your site. If you do your homework you
can even share parts of these objects inside your Web-MVC application
to keep the code DRY. Those proxies keep authentication logic out of
your service class.</li>
<li>Use the remote facade pattern to implement a few, powerful methods
that delegate the service request to underlying domain objects. Never
ever publish direct access to domain objects with your webservices.
As a rule of thumb, talking to a webservice during a logical
operation should never involve more than one or two calls. The first
call is for data fetching, the second for data saving. Authentication
should be handled via HTTP Authentication to save an additional call.</li>
</ul>
<p>If you follow these simple rules, you should get around the performance
issues that generally come with webservices, without loosing flexibility
at all.</p>
</div>]]></description>
            <pubDate>Mon, 12 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/01/07/seven-things.html</link>
            <guid>http://www.whitewashing.de/2009/01/07/seven-things.html</guid>
            <title><![CDATA[Seven Things]]></title>
            <description><![CDATA[<div class="section" id="seven-things">
<h1>Seven Things</h1>
<p>I have been tagged by
<a class="reference external" href="http://dolfschimmel.freeaqingme.com/?p=78">Freeaqingme</a> and the blog
letter machinery. So read on for seven things you probably may not know
about me.</p>
<ul class="simple">
<li>I will get my degree in some weeks, currently intensively writting on
my thesis. My major is economics though. I probably won’t get a job
with that sooner or later. I actually don’t want to, I have a job as
programmer already.</li>
<li>One christmas many years ago (Pentium PCs to 200Mhz were the coolest
thing around) i wished and wished for a computer for playing Command
and Conquer and stuff. What i got was a 3/86 i could only run crap
with. So i had to start programming.</li>
<li>In 11th grade (7 years ago) I took part in the german computer
science olympics (<a class="reference external" href="http://www.bwinf.de/uploads/media/bwi20/runde1/20bwinf.pdf">exercise still
online</a>)
using PHP and writing thousands of lines of nested aray and for loop
code and print the solution to the browser. No need to say I utterly
failed, because I didn’t know a bit about algorithms, pointers and
objects at all.</li>
<li>I have only learned about what good programming practices are (OO,
functional, whatever) really means in the last two years, spending
almost every free minute of those many i had on projects to test
around with patterns and programming styles.</li>
<li>I went to my first conference last year september, the IPC in Mainz,
getting to know lots of great people in the community.</li>
<li>I don’t have a license at all (<a class="reference external" href="http://blog.libssh2.org/index.php?/archives/122-Seven-Things.html">Reference to
Sara</a>).
I am afraid of driving cars, although I drive my bike through the
biggest crossroads in town like nuts.</li>
<li>I am a timeline oriented reader, having made me masterplans to read
both all the Discworld and Ian Rankin novels in the correct order to
not miss a single reference.</li>
</ul>
<p>Its sad that everyone I would want to tag was already tagged by someone
else, still for the head count:</p>
<ul class="simple">
<li><a class="reference external" href="http://weierophinney.net/matthew/">Matthew Weierophinney</a>, because
he helped me understand Zend Framework alot.</li>
<li><a class="reference external" href="http://www.dasprids.de/">Ben Scholzen</a>, because he is a fun guy to
be around <strong>#zftalk.dev</strong>.</li>
<li><a class="reference external" href="http://www.thomasweidner.com/flatpress/">Thomas Weidner</a>, because
I like his dedication towards his ZF components.</li>
<li><a class="reference external" href="http://kore-nordmann.de/blog.html">Kore Nordmann</a>, Bastian Feder
and Thomas Weinert, because I had great discussions with him on IPC.</li>
<li><a class="reference external" href="http://codeutopia.net/blog/">zomg aka Jani</a> because of his skills
to be referenced by PHPDeveloper.org (joke) and the good IRC
discussions.</li>
<li><a class="reference external" href="http://blogs.sun.com/netbeansphp/">Petr Pisl</a> because of the
awesome NetBeans PHP support.</li>
</ul>
</div>]]></description>
            <pubDate>Wed, 07 Jan 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/03/11/using-zend-soap-server-and-autodiscover-in-a-controller.html</link>
            <guid>http://www.whitewashing.de/2009/03/11/using-zend-soap-server-and-autodiscover-in-a-controller.html</guid>
            <title><![CDATA[Using Zend_Soap Server and Autodiscover in a Controller]]></title>
            <description><![CDATA[<div class="section" id="using-zend-soap-server-and-autodiscover-in-a-controller">
<h1>Using Zend_Soap Server and Autodiscover in a Controller</h1>
<p>I am in a dilemma. I have condemned the usage of Zend_Soap_Server (or
any other webservice server handler) <a class="reference external" href="http://www.whitewashing.de/blog/articles/106">inside a Model-View-Controller
application</a> before.
Still I get questions about <a class="reference external" href="http://www.whitewashing.de/blog/articles/65">my old Zend_Soap_Server and
Zend_Soap_AutoDiscover
example</a> not working in
the MVC scenario. The following example provides you with a working Soap
server inside a Zend_Controller_Action, although I discourage the use
of it and would suggest using a dedicated script outside the dispatching
process to gain multitudes of performance, which webservices often
require.</p>
<blockquote>
<div><div class="highlight-python"><pre>require_once &quot;/path/to/HelloWorldService.php&quot;;

class MyDiscouragedSoapServerController extends Zend_Controller_Action
{
    public function serverAction()
    {
        $server = new Zend_Soap_Server(&quot;http://example.com/pathto/wsdl&quot;);
        $server-&gt;setClass('HelloWorldService');
        $server-&gt;handle();
    }

    public function wsdlAction()
    {
        $wsdl = new Zend_Soap_AutoDiscover();
        $wsdl-&gt;setUri('http://example.com/pathto/server');
        $wsdl-&gt;setClass('HelloWorldService');
        $wsdl-&gt;handle();
    }
}</pre>
</div>
</div></blockquote>
<p>Now all you have to do is create two routes, one that makes
<strong>http://example.com/pathto/server</strong> point to
<strong>MyDiscouragedSoapServerController::serverAction</strong> and the other route
that makes <strong>http://example.com/pathto/wsdl</strong> point to
<strong>MyDiscouragedSoapServerController::wsdlAction</strong>. The wrong version
(Version Mismatch) error comes from sending a request for the WSDL file
to the actual Soap Server, which he doesn’t like.</p>
</div>]]></description>
            <pubDate>Wed, 11 Mar 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/03/27/test-your-legacy-php-application-with-function-mocks.html</link>
            <guid>http://www.whitewashing.de/2009/03/27/test-your-legacy-php-application-with-function-mocks.html</guid>
            <title><![CDATA[Test your Legacy PHP Application with Function Mocks!]]></title>
            <description><![CDATA[<div class="section" id="test-your-legacy-php-application-with-function-mocks">
<h1>Test your Legacy PHP Application with Function Mocks!</h1>
<p>Much talking is going on about Unittesting, Mocks and TDD in the PHP
world. For the most this discussions surround object-oriented PHP code,
frameworks and applications.</p>
<p>Yet I would assert that the reality for PHP developers (me included) is
dealing with PHP 4, PHP 5 migrated, or non-object oriented legacy
applications which are near to impossible to bring under test. Still
this code works, is in production and needs maintenance and possibly
extension for new features.</p>
<p>For example many applications may still use <strong>mysql_*</strong> functions at
length inside their model or have multiple nested function levels
(Example: Wordpress). <a class="reference external" href="http://pecl.php.net/package/runkit">Runkit</a> to
the rescue: A PECL extension that can hack your running PHP code, such
that method or functions are repointed to execute new implementations.
Using this extension you can actually mock out internal PHP functions,
which is great to bring legacy code under test.</p>
<p>Consider this following proof of concept, <a class="reference external" href="http://github.com/padraic/runkit/tree/master">using the Runkit extension
build by Padraic Brady</a>
(the one from pecl.php.net does not compile on PHP 5.2), which replaces
the functionality of <strong>mysql_query()</strong>. You have to set the following
option in your php.ini: <strong>runkit.internal_override = On</strong> for this to
work. By default only user-defined functions may be overwritten by
Runkit.</p>
<blockquote>
<div><div class="highlight-python"><pre>class FunctionMocker
{
    protected $_mockedFuncBehaviourMap = array();

    public function mock($funcName, $return=null)
    {
        $newFuncCode = 'return &quot;'.$return.'&quot;;';

        $renamedName = &quot;__&quot;.$funcName.&quot;_mockOriginalCopy&quot;;
        runkit_function_copy($funcName, $renamedName);
        runkit_function_redefine($funcName, '', $newFuncCode);

        $this-&gt;_mockedFuncBehaviourMap[$funcName] = $renamedName;
    }

    public function reset()
    {
        foreach($this-&gt;_mockedFuncBehaviourMap AS $funcName =&gt; $renamedName) {
            runkit_function_remove($funcName);
            runkit_function_copy($renamedName, $funcName);
            runkit_function_remove($renamedName);
        }
        $this-&gt;_mockedFuncBehaviourMap = array();
    }
}

$mocker = new FunctionMocker();
$mocker-&gt;mock('mysql_query', 'hello world!');

echo mysql_query(); // hello world

$mocker-&gt;reset();

mysql_query(); // error</pre>
</div>
<p>This example, only allows for string return values of the mock and
has no support for replacing the arguments of the mocked function.
Also chaining of different return values based on input or call
number might be interesting. Some kind of Code Generator Tool would
have to be implemented to support this functionality. Additionally
Assertions and Verifying should be implemented for the function
arguments. All in all this would allow to mock functions as you
would mock interfaces/classes, which would be a great addition for
all those legacy applications that use procedural PHP.</p>
<p>Additionally what the real killer for runkit would be: The
possibility to insert PHP callbacks instead of real PHP code into
the <strong>runkit_function_redefine</strong>.</p>
</div></blockquote>
</div>]]></description>
            <pubDate>Fri, 27 Mar 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/03/10/speaking-about-framework-quality-on-the-ipc-spring-09.html</link>
            <guid>http://www.whitewashing.de/2009/03/10/speaking-about-framework-quality-on-the-ipc-spring-09.html</guid>
            <title><![CDATA[Speaking about Framework Quality on the IPC Spring 09]]></title>
            <description><![CDATA[<div class="section" id="speaking-about-framework-quality-on-the-ipc-spring-09">
<h1>Speaking about Framework Quality on the IPC Spring 09</h1>
<p>Just a short notice, my thesis is taking its last breath, I will be
speaking on the <a class="reference external" href="http://www.phpconference.com">IPC Spring 09
conference</a> in Berlin end of may this
year on Framework Quality and Unittests:</p>
<blockquote>
<div><dl class="docutils">
<dt><strong>Framework Quality: Unit-Tests as silent witness</strong></dt>
<dd>Unit-Tests are often overlooked in framework discussions that focus</dd>
</dl>
<p>on features, performance, tools or database abstraction. However
they are a silent witness on how poor or well frameworks are
designed. In this presentation we will look at the testsuites of the
big players in the PHP framework business - Zend Framework,
ezComponents, Symfony and CakePHP - and reveal their hidden secrets.</p>
</div></blockquote>
<p>This talk will make heavy use of the <a class="reference external" href="https://github.com/beberlei/puma/tree">PHP Unittest and Metrics
Aggregator tool</a>, which i haven
written on several times. For both CakePHP and Symfony extensions for
their testtools may have to be written.</p>
<p>I am really excited for my first time being speaker on a conference and
looking forward to see you at IPC.</p>
</div>]]></description>
            <pubDate>Tue, 10 Mar 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/10/05/php-codesniffer-for-netbeans-v0-2.html</link>
            <guid>http://www.whitewashing.de/2009/10/05/php-codesniffer-for-netbeans-v0-2.html</guid>
            <title><![CDATA[PHP CodeSniffer for Netbeans v0.2]]></title>
            <description><![CDATA[<div class="section" id="php-codesniffer-for-netbeans-v0-2">
<h1>PHP CodeSniffer for Netbeans v0.2</h1>
<p>I finally found some time to spend some time on the <a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements/">PHP CodeSniffer for
Netbeans
plugin</a>.
Previously the plugin used an unnecessary API which restricted the use
to Netbeans 6.7.0 only. This API was removed so that the plugin should
now work with all Netbeans Versions &gt;= 6.7.0.</p>
<p>Additionally when working the previous version would scan every PHP
script on a file per file basis when the all projects or main projects
filters were activated. This rendered made the plugin almost useless. In
the current version scans of filters that contain more than one file are
blocked. That means you will only see Coding Violations when you enable
the “Current File” filter. Using any other filter will just do nothing
and won’t put your Netbeans in permanent hibernation mode (aka useless
mode).</p>
<p>There is also some preference <strong>“phpcs.codingStandard”</strong> using the
<strong>`NbPreferences
API &lt;http://bits.netbeans.org/dev/javadoc/org-openide-util/org/openide/util/NbPreferences.html&gt;`_</strong>
which allows to configure the coding standard. [STRIKEOUT:However this
feature was contributed by <a class="reference external" href="http://manuel-pichler.de/">Manuel
Piechler</a> and I don’t yet understand how I
can manipulate it. Maybe someone knows how (*Looking in Mapis general
direction*)?] By default the Zend Coding Standard is used.</p>
<p><strong>Update:</strong> Coding Standard can be changed by hacking into the config
file .netbeans/6.7/config/Preferences.properties setting
“phpcs.CodingStandard=”. Additionally I fixed several bugs with the
inline highlighting that did not refresh when lines in the file changed.</p>
</div>]]></description>
            <pubDate>Mon, 05 Oct 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/12/19/trying-a-two-step-pear-phar-approach-to-develop-and-deploy.html</link>
            <guid>http://www.whitewashing.de/2009/12/19/trying-a-two-step-pear-phar-approach-to-develop-and-deploy.html</guid>
            <title><![CDATA[Trying a Two Step PEAR/PHAR approach to develop and deploy]]></title>
            <description><![CDATA[<div class="section" id="trying-a-two-step-pear-phar-approach-to-develop-and-deploy">
<h1>Trying a Two Step PEAR/PHAR approach to develop and deploy</h1>
<p>With PHP 5.3 the PHAR extension is a pretty powerful concept for all
your deployment needs, however it does not tell the complete story.
Frameworks, Libraries and many different of them are used throughout
applications and in recent times people even began to chery-pick the
best components from each of the frameworks and package them together.
With Pirum being a simple PEAR channel server there is also momentum for
projects to distribute their code via PEAR.</p>
<p>However PEAR is mostly used in the server-wide configuration use-case,
which is not very useful if you plan to distribute your complete
application in one PHAR file. I just recently had the idea for this
scenario, so please bear with me and add all the feedback and comments
you can come up with. I tested this with the ongoing rewrite of my blog
software.</p>
<p>First we’ll add a new user that we develop our application with:</p>
<div class="highlight-python"><pre>sudo useradd -m -g www-data whitewashing
sudo passwd whitewashing
su - whitewashing</pre>
</div>
<p>Now there is the possibility that with this user PHP and PEAR is not in
your $PATH environment, so you might have to add it. In my case on Ubuntu
i also had to switch the console from /bin/sh to /bin/bash for this
user. Then we need to setup our application, I am going to use the Zend
Framework project style here but with a little twist. We will add a
distinction between vendor and project libraries by adding a <em>vendor</em>
directory into the main folder.</p>
<p>But first we create a folder for our application, and create a Zend
Framework project in the subfolder “trunk”, which will be the focus of
our development.</p>
<div class="highlight-python"><pre>whitewashing@desktop:~$ mkdir whitewashing
whitewashing@desktop:~$ zf create project whitewashing/trunk
Creating project at /home/whitewashing/whitewashing/trunk
whitewashing@desktop:~$ mkdir whitewashing/trunk/vendor</pre>
</div>
<p>Now we can configure an Apache virtual host to point to our
/home/whitewashing/whitewashing/public directory, i call this
“whitewashing-dev” add it to my /etc/hosts and can visit the dummy
project page.</p>
<p>We then configure our PEAR installation for the specific application
user and re-configure the bin and php library paths:</p>
<div class="highlight-python"><pre>whitewashing@desktop:~$ pear create-config /home/whitewashing/ .pearrc
whitewashing@desktop:~$ pear config-set php_dir /home/whitewashing/whitewashing/trunk/vendor
whitewashing@desktop:~$ pear config-set bin_dir /home/whitewashing/whitewashing/trunk/bin</pre>
</div>
<p>This configuration assumes that we will install all our stuff into our
development trunk. From there also the PEAR installed libraries might be
copied into branches or tags. PEAR Project tests, configuration and
web-files will still be put by default under $HOME/pear/*. We don’t
need them for our applications.</p>
<p>Now we install all the dependencies our project needs, in this case Zend
Framework, Doctrine 2, HTML Purifier:</p>
<div class="highlight-python"><pre>whitewashing@desktop:~$ pear channel-discover pear.zfcampus.org
whitewashing@desktop:~$ pear install zfcampus/zf-alpha
whitewashing@desktop:~$ pear channel-discover htmlpurifier.org
whitewashing@desktop:~$ pear install hp/HTMLPurifier
whitewashing@desktop:~$ pear channel-discover pear.phpdoctrine.org
whitewashing@desktop:~$ pear install pear.phpdoctrine.org/DoctrineORM-2.0.0</pre>
</div>
<p>Now we have all three of the packages installed in our project folder
<cite>whitewashing/trunk/vendor</cite>, see:</p>
<div class="highlight-python"><pre>whitewashing@desktop:~$ ls -aFl whitewashing/trunk/vendor/
total 680
drwxr-xr-x  7 whitewashing www-data   4096 2009-12-13 14:45 ./
drwxr-xr-x  8 whitewashing www-data   4096 2009-12-13 14:36 ../
drwxr-xr-x  3 whitewashing www-data   4096 2009-12-13 14:43 .channels/
-rw-r--r--  1 whitewashing www-data     57 2009-12-13 14:45 .depdb
-rw-r--r--  1 whitewashing www-data      0 2009-12-13 14:45 .depdblock
drwxr-xr-x  5 whitewashing www-data   4096 2009-12-13 14:45 Doctrine/
-rw-r--r--  1 whitewashing www-data 582208 2009-12-13 14:45 .filemap
drwxr-xr-x 20 whitewashing www-data   4096 2009-12-13 14:39 HTMLPurifier/
-rw-r--r--  1 whitewashing www-data    629 2009-12-13 14:39 HTMLPurifier.autoload.php
-rw-r--r--  1 whitewashing www-data    274 2009-12-13 14:39 HTMLPurifier.auto.php
-rw-r--r--  1 whitewashing www-data    545 2009-12-13 14:39 HTMLPurifier.func.php
-rw-r--r--  1 whitewashing www-data   9299 2009-12-13 14:39 HTMLPurifier.includes.php
-rw-r--r--  1 whitewashing www-data    955 2009-12-13 14:39 HTMLPurifier.kses.php
-rw-r--r--  1 whitewashing www-data   8831 2009-12-13 14:39 HTMLPurifier.php
-rw-r--r--  1 whitewashing www-data  11901 2009-12-13 14:39 HTMLPurifier.safe-includes.php
-rw-r--r--  1 whitewashing www-data      0 2009-12-13 14:45 .lock
drwxr-xr-x  8 whitewashing www-data   4096 2009-12-13 14:43 .registry/
drwxr-xr-x 59 whitewashing www-data   4096 2009-12-13 14:36 Zend/
-rw-r--r--  1 whitewashing www-data  19537 2009-12-13 14:36 zf.php</pre>
</div>
<p>And both Doctrine and ZF registered their binary CLi tools inside the
<cite>whitewashing/trunk/bin/</cite> folder:</p>
<div class="highlight-python"><pre>whitewashing@desktop:~$ ls -aFl bin/
total 20
drwxr-xr-x 2 whitewashing www-data 4096 2009-12-13 14:45 ./
drwxr-xr-x 8 whitewashing www-data 4096 2009-12-13 14:36 ../
-rwxr-xr-x 1 whitewashing www-data   50 2009-12-13 14:45 doctrine*
-rwxr-xr-x 1 whitewashing www-data  169 2009-12-13 14:45 doctrine.php*
-rwxr-xr-x 1 whitewashing www-data 1511 2009-12-13 14:36 zf*</pre>
</div>
<p>We now have the full control over the versions of our dependencies, we
can call “pear upgrade ” whenever we want to update one of the ZF,
Doctrine or HtmlPurifier libraries inside our application.</p>
<p>Now some magic is gonna happen, we start to develop our application and
such which is all not really interesting for this topic. At some point
we want to package it all up into a PHAR file and distribute it. We want
to package our application in one big phar file. We also want to make
sure that the configuration files in
<cite>whitewashing/trunk/application/configs/</cite> are not distributed, but have
to be created on the server and are kept that way. We could write an
installer script for this configuration management.</p>
<p>The reference for PHAR files is the PHP Manual for the Basics and Cal
Evans’ two posts
(<a class="reference external" href="http://blog.calevans.com/2009/07/19/lessons-in-phar/">1</a>,
<a class="reference external" href="http://blog.calevans.com/2009/07/26/packaging-zend-framework-as-a-phar-revisited/">2</a>)
on this topic, aswell as <a class="reference external" href="http://geekmonkey.org/articles/PHP_Archives">a post on
Geekmonkey</a>. Contrary to
most other PHP extensions, PHAR has an extensive documentation, however
its not organized terribly well. Also there are no real use-cases and
scenarios discussed, methods are only looked at in isolation. Cals posts
are very good on understanding how to package up different libraries,
but there is no word on distributing web applications. That is where the
Geekmonkey post comes in to wire it all together.</p>
<p>For a Zend Framework application that should have both a web and a cli
(cronjobs) entry point into the application we need a specific stub file
for the PHAR bootstrapping. A stub is a little PHP script that is
executed whenever your PHAR file is included into your php script. It is
essentially a front-controller for your PHAR application. It also has
mount capabilities that allow to import files or directories from
outside into the PHAR context. This is a powerful feature that is
required to distribute configurable applications like our blog.</p>
<p>This screenshot shows how the application is currently structured in
development mode. In production its structure should look like:</p>
<div class="highlight-python"><pre>whitewashing
|--application
|  |--configs
|     |-- my application config files are all here...
|--bin
|  |--whitewashing.php
|--public
|  |--index.php
|  |--.htaccess
|--whitewashing.phar</pre>
</div>
<p>The whitewashing.php and index.php files are the application entry
points that only include the phar file and trigger the application
bootstrapping that will be included in the Stub file. They both look
like:</p>
<div class="highlight-python"><pre>&lt;?php
define('EXTERNAL_APPLICATION_ROOT', __DIR__.&quot;/../&quot;);
include EXTERNAL_APPLICATION_ROOT.&quot;/whitewashing.phar&quot;;</pre>
</div>
<p>Including a PHAR file essentially has two consequences:</p>
<ul class="simple">
<li>The PHAR path will be added to your include path.</li>
<li>The stub file will be executed.</li>
</ul>
<p>Our application stub looks like this:</p>
<div class="highlight-python"><pre>&lt;?php

if(defined('EXTERNAL_APPLICATION_ROOT')) {
    // Mount the external application/configs directory as config if it exists.
    if (file_exists(EXTERNAL_APPLICATION_ROOT.&quot;/application/configs&quot;)) {
        Phar::mount(&quot;application/configs&quot;, EXTERNAL_APPLICATION_ROOT.&quot;/application/configs&quot;);
    }
}

/** Zend_Loader_Autoloader */
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();

if (php_sapi_name() == &quot;cli&quot;) {
    require_once 'bin/whitewashing.php';
} else {
    require_once 'public/index.php';
}

__HALT_COMPILER();</pre>
</div>
<p>The first bit of the stub mounts the external application configs
directory into the stub and hides possible directories that are present
at this location in the PHAR file. This allows us to distribute our
application with a default configuration, but allows any user to replace
the configuration files to fit the application to his need.</p>
<p>The second bit loads Zend Framework Autoloader that is required by the
bootstrapping mechanism. The third bit decides whether this request is
executed from the CLI- or the Web-Entry point of the application. The
fourth bit, <tt class="docutils literal"><span class="pre">__HALT_COMPILER();</span></tt> is a technically required call inside
your stub-file.</p>
<p>Now that we have a stub-file for our application, we can package it and
distribute it. I am using a modified version of Cal Evans example for
this. I have extracted his directory traversal to find all the relevant
into a re-usable FilterIterator implementation. I <a class="reference external" href="https://gist.github.com/3b20264b857dbdabf526">pasted my package.php
a Gist</a> on Github. Now
this should probably be put into the build context of your application,
possibly as a phing or ant task or something alike.</p>
<p>Now what this build process does not manage is the creation of the
application entry point php and .htaccess files, but since they won’t
ever change its easy to add them to the build directory for now. An even
more sophisticated version of the build script would lead to the
creation of an additional tar.gz of the complete application folder. Our
deployment process would then be as easy as:</p>
<ul class="simple">
<li>If the application is not installed yet, unpack the tarball into its
location.</li>
<li>If the application should be updated, just replace the PHAR file.</li>
</ul>
<p>If you need the ability to go back to any version of your application
you could make use of symlinks.</p>
</div>]]></description>
            <pubDate>Sat, 19 Dec 2009 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/07/30/php-codesniffer-support-for-netbeans.html</link>
            <guid>http://www.whitewashing.de/2009/07/30/php-codesniffer-support-for-netbeans.html</guid>
            <title><![CDATA[PHP CodeSniffer Support for Netbeans]]></title>
            <description><![CDATA[<div class="section" id="php-codesniffer-support-for-netbeans">
<h1>PHP CodeSniffer Support for Netbeans</h1>
<p>I dived into the code of my new favorite IDE
<a class="reference external" href="http://www.netbeans.org">Netbeans</a> these last days and came up with
an <a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements/tree/master">extension
module</a>,
which adds PHP CodeSniffer Support on a per file basis to make my life
much easier. It shows warnings and errors as annotations to the Editor
and marks the affected lines in yellow and red.</p>
<p><a class="reference external" href="http://cloud.github.com/downloads/beberlei/netbeans-php-enhancements/netbeans_cs_support.png">|image0|</a></p>
<p>[STRIKEOUT:My Java skills being very bad, it will only work on Linux
currently, since the PHP Code Sniffer “binary” is hardcoded into the
Java Source code. You have to create a “/usr/bin/phpcs2” executable,
which is a wrapper that looks like:]</p>
<p>With Manuals extensions (see the comments) the module now works without
the wrapper script. It might even work under Windows now. Yet now the
Zend Coding standard is enforced though. I am working on making that one
configurable next.</p>
<p>You can install the <a class="reference external" href="http://github.com/beberlei/netbeans-php-enhancements/downloads">NBM module install
file</a>
from the GitHub repository into Netbeans and it “should” work then.</p>
<p>I hope to get more familiar with Netbeans in the future to add some more
PHP tools and enhance Code Sniffer support.</p>
</div>]]></description>
            <pubDate>Thu, 30 Jul 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2009/07/04/using-symfony-dependency-injection-with-zend-application.html</link>
            <guid>http://www.whitewashing.de/2009/07/04/using-symfony-dependency-injection-with-zend-application.html</guid>
            <title><![CDATA[Using Symfony Dependency Injection with Zend_Application]]></title>
            <description><![CDATA[<div class="section" id="using-symfony-dependency-injection-with-zend-application">
<h1>Using Symfony Dependency Injection with Zend_Application</h1>
<p>As a follow-up to my <a class="reference external" href="http://www.whitewashing.de/blog/articles/117">recent
post</a> on Dependency
Injection containers and Zend_Application I was eager to find out if
its possible to integrate the new <a class="reference external" href="http://components.symfony-project.org/dependency-injection/">Symfony Dependency Injection
Container</a>
into the Zend Framework. To my surprise it’s possible without having to
make any changes to one of the two components. An example use-case would
look like:</p>
<blockquote>
<div><div class="highlight-python"><pre>$container = new sfServiceContainerBuilder();

$loader = new sfServiceContainerLoaderFileXml($container);
$loader-&gt;load(APPLICATION_PATH.'/config/objects.xml');

$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/config/application.xml'
);
$application-&gt;getBootstrap()-&gt;setContainer($container);
$application-&gt;bootstrap()
            -&gt;run();</pre>
</div>
</div></blockquote>
<p>Resources instantiated by Zend_Application are then injected into the
container by the name of the resource and are given the resource
instance. Any object from the Symfony container can then use these
dependencies in their object setup. The only drawback of the integration
is the fact that the Symfony Container is case-sensitive in regards to
the service names but Zend_Application lower-cases all service before
injecting them into the container. The following code is a restatement
of my previous example of a <strong>MyModel</strong> class which requires a
<strong>Zend_Db</strong> and <strong>Zend_Cache</strong> constructor argument.</p>
<blockquote>
<div><div class="highlight-python"><pre>$container-&gt;register('myModel', 'MyModel')
          -&gt;addArgument(new sfServiceReference('db'))
          -&gt;addArgument(new sfServiceReference('cache'));</pre>
</div>
</div></blockquote>
<p>Access to a MyModel instance with its dependencies is then granted
through the call <strong>$container-&gt;myModel</strong> throughout the application.
Make sure to call this after running Zend_Application::bootstrap, so
that the Resource dependencies are injected first.</p>
</div>]]></description>
            <pubDate>Sat, 04 Jul 2009 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/02/12/pdt-back-to-easyeclipse-with-php-extension.html</link>
            <guid>http://www.whitewashing.de/2008/02/12/pdt-back-to-easyeclipse-with-php-extension.html</guid>
            <title><![CDATA[PDT: Back to easyeclipse with PHP extension]]></title>
            <description><![CDATA[<div class="section" id="pdt-back-to-easyeclipse-with-php-extension">
<h1>PDT: Back to easyeclipse with PHP extension</h1>
<p>I am disappointed by <a class="reference external" href="http://www.eclipse.org/pdt/">PDT</a> for Eclipse.
The current version strikes my rather old machine with “just” 512mb to
death. Building projects is not possible even when assigning eclipse all
my available memory, because of an Java Heap Error (<a class="reference external" href="http://blog.wolff-hamburg.de/archives/20-Migrating-to-PDT.html">See this blog
post</a>).
This effectively hinders you to use all the completion and hint features,
because PDT does not know about any functions, classes and their phpdoc
descriptions.</p>
<p>PDT is also missing some very important features. Marking all occurrences
of a function, class, constant or variable on click for example. PHP
Errors and Warnings are display in a way so that you won’t find them and
if you do, you won’t understand what they mean.</p>
<p>So I am going back to my easyeclipse with php combination, which always
worked well, the only problem being that it is no longer under active
development. At least it has all the features I need for now.</p>
</div>]]></description>
            <pubDate>Tue, 12 Feb 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/05/25/introducing-zend-controller-scaffolding.html</link>
            <guid>http://www.whitewashing.de/2008/05/25/introducing-zend-controller-scaffolding.html</guid>
            <title><![CDATA[Introducing: Zend Controller Scaffolding]]></title>
            <description><![CDATA[<div class="section" id="introducing-zend-controller-scaffolding">
<h1>Introducing: Zend Controller Scaffolding</h1>
<p>In the last couple of weeks I <a class="reference external" href="http://codecaine.co.za/posts/form-generation-with-zend-form-part-2/">came across the
idea</a>
of building a little component for scaffolding in Zend Framework. After
playing around with this idea a little I came up with an
Zend_Controller_Scaffolding object, which extends the
Zend_Controller_Action object.</p>
<p>It takes any Zend_Db_Table_Abstract object and generates create and
update forms using Zend_Form and displays them in the Controller. The
component is very easy to use, as this example shows:</p>
<blockquote>
<div><div class="highlight-python"><pre>class SomeController extends WW_Controller_Scaffolding {
    public function init() {
        $this-&gt;setScaffolding(new ZendDbTableModel(), $options);
    }
}</pre>
</div>
</div></blockquote>
<p>You now have access to the following actions of the controller:
some/create some/edit some/delete and some/index (some/list). They
handle all your model editing dreams.</p>
<p>All you have to own is the WW_Controller_Scaffolding Library Class and
a folder of scaffolding view templates both of which are <a class="reference external" href="http://www.beberlei.de/sources/zend_controller_scaffolding-0.5.5.tar.gz">bundled in an
archive you can
download</a>.</p>
<p><strong>Download</strong></p>
<ul class="simple">
<li><a class="reference external" href="http://www.beberlei.de/sources/zend_controller_scaffolding-0.5.5.tar.gz">Download Version
0.5.5</a></li>
</ul>
<p><strong>Changes</strong></p>
<ul class="simple">
<li>0.5.5: Put Component into own Namespace (WW = Whitewashing). Make it
possible to hide fields in the list via the options. Allow to specify
scaffolding view scripts folder via options.</li>
</ul>
<p><strong>Install &amp; Usage</strong></p>
<blockquote>
<div><div class="highlight-python"><pre>Untar the two folders include/ and views/ into your
Zend Framework project application directory.

Make sure the include folder is in your Zend_Loader
include path or move the Scaffolding.php so that it
is placed in your library include path.

Define each Controller that should be a Scaffolding Interface
as:

class SomeController extends WW_Controller_Scaffolding {
    public function init() {
        $this-&gt;setScaffolding(new ZendDbTableModel(), $options);
    }
}

Where $options is an array or Zend_Config object with any of the following keys:

  'allow_edit_primary_key' True/false - Whether the form allows you to set the
                          Primary Key fields or not

 'field_names' an Array of the Database Tables field names mapped to Label Names

 'hide_list_fields' Array of database table field names that should not be displayed in the list overview.

 'checkbox' an Array of Database Table field names that should be represented
            as Checkbox. Useful for TINYINT(1) fields that represent boolean decisions.

 'view_folder' Sometimes you want to use different views for scaffolding in one project. Use
               this variable and copy the scaffolding folder for each component you want to
               change the view basics for.</pre>
</div>
</div></blockquote>
<p><strong>Todos &amp; Problems:</strong></p>
<ul class="simple">
<li>Many To Many Relationships are not implemented yet (Using
MultiSelec).</li>
<li>Compound Keys are probably not working correctly</li>
<li>Relationships on non-primary key fields probably don’t work as
expected</li>
<li>Relationships with lots of data are not scaled down for easy
administration.</li>
</ul>
<p>Please report any bugs and feature requests or recommendations to
<strong>kontakt at beberlei dot de</strong>.</p>
</div>]]></description>
            <pubDate>Sun, 25 May 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/05/18/my-2-cents-on-zend-search-lucene-update-problems.html</link>
            <guid>http://www.whitewashing.de/2008/05/18/my-2-cents-on-zend-search-lucene-update-problems.html</guid>
            <title><![CDATA[My 2 cents on Zend_Search_Lucene Update Problems]]></title>
            <description><![CDATA[<div class="section" id="my-2-cents-on-zend-search-lucene-update-problems">
<h1>My 2 cents on Zend_Search_Lucene Update Problems</h1>
<p><a class="reference external" href="http://framework.zend.com">Zend_Search_Lucene</a> (or Lucene in
general) does not support an update statement, therefore we must check
via find() if a specific article that should be updated already exists.</p>
<p>Numerous solutions exist for this problem (<a class="reference external" href="http://devzone.zend.com/content/zendcon_07_slides/Evron_Shahar_Indexing_With_Zend_Search_Lucene-ZendCon07.pdf">for example this PDF
Tutorial by a Zend
Programmer</a>).
Mine looks as follows. The first thing is to Set an Analyzer other from
the default one. The Default Analyzer only looks at letters, not at
numbers.</p>
<blockquote>
<div><div class="highlight-python"><pre>Zend_Search_Lucene_Analysis_Analyzer::setDefault(new
    Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive()
);
$index = Zend_Search_Lucene::open('/path/to/index/directory');</pre>
</div>
</div></blockquote>
<p>We can now save an identifier containing letters and numbers, for
example the md5 string of the Article Database ID.</p>
<blockquote>
<div><div class="highlight-python"><pre>$doc = new Zend_Search_Lucene_Document();
$field = Zend_Search_Lucene_Field::Keyword('id', md5($data['id']));
$doc-&gt;addField($field);
$index-&gt;addDocument($doc);</pre>
</div>
</div></blockquote>
<p>Before updating an entry you have to delete any entry that has been
indexed before:</p>
<blockquote>
<div><div class="highlight-python"><pre>$hits = $index-&gt;find('id:'.md5($articleID));
foreach($hits AS $hit) {
    $index-&gt;delete($hit-&gt;id);
}</pre>
</div>
</div></blockquote>
<p>The <a class="reference external" href="http://devzone.zend.com/content/zendcon_07_slides/Evron_Shahar_Indexing_With_Zend_Search_Lucene-ZendCon07.pdf">Tutorial Talk on Search
Lucene</a>
(given above) uses an extended version of this delete routine snippet
that also checks if an article is up to date and does not have to be
reindexed and deletes multiple entries of one article.</p>
</div>]]></description>
            <pubDate>Sun, 18 May 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/05/17/integrated-zend-layout-into-this-blog.html</link>
            <guid>http://www.whitewashing.de/2008/05/17/integrated-zend-layout-into-this-blog.html</guid>
            <title><![CDATA[Integrated Zend_Layout into this blog]]></title>
            <description><![CDATA[<div class="section" id="integrated-zend-layout-into-this-blog">
<h1>Integrated Zend_Layout into this blog</h1>
<p>I finished with integrating Zend_Layout into this blog software today.
At first I thought it is quite hard to use especially if you want to
integrate dynamic navigational contents depending on the current
module/controller/action setup. But I came up with a combination of
actionStack and Named Response Sections as <a class="reference external" href="http://framework.zend.com/manual/en/zend.layout.quickstart.html#zend.layout.quickstart.mvc">described in the ZF
Documentation of the Layout
component</a>,
which is quite easy to understand, use and extend.</p>
<p>At each of the major Controllers I put different actions from a specific
Navigation Controller on the
<a class="reference external" href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.actionstack">ActionStack</a>
(mostly global per Controller using the init() class method).</p>
<p>A typical controller looks like this:</p>
<blockquote>
<div><div class="highlight-python"><pre>class BlogController extends Zend_Controller_Action
{
    public function init()
    {
        $this-&gt;_helper-&gt;actionStack('tagcloud', 'Navigation');
        $this-&gt;_helper-&gt;actionStack('userinfo', 'Navigation');
    }
}</pre>
</div>
</div></blockquote>
<p>The NavigationController looks like this:</p>
<blockquote>
<div><div class="highlight-python"><pre>class NavigationController extends Zend_Controller_Action
{
    public function tagcloudAction()
    {
        // Do not render the content of this action to the default output.
        $this-&gt;getHelper(&quot;ViewRenderer&quot;)-&gt;setNoRender();

        [...]

        // Append content to secondaryNavigation named response section
        $this-&gt;getResponse()-&gt;append('secondaryNavigation', $this-&gt;view-&gt;render('navigation/tagcloud.phtml'));
    }
}</pre>
</div>
</div></blockquote>
<p>The layout.pthml then just calls certain named sections, for example &lt;=?
$this-&gt;layout()-&gt;secondaryNavigation; ?&gt;</p>
</div>]]></description>
            <pubDate>Sat, 17 May 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/05/17/using-zend-http-client-to-ping-technorati.html</link>
            <guid>http://www.whitewashing.de/2008/05/17/using-zend-http-client-to-ping-technorati.html</guid>
            <title><![CDATA[Using Zend_Http_Client to Ping Technorati]]></title>
            <description><![CDATA[<div class="section" id="using-zend-http-client-to-ping-technorati">
<h1>Using Zend_Http_Client to Ping Technorati</h1>
<p>Send a ping to Technorati manually is a pain in the ass. Writing a
little Method that handles this functionality for your own blog software
is quite easy. Call the following method after you created or updated a
post of yours:</p>
<blockquote>
<div><div class="highlight-python"><pre>private function _pingTechnorati()
{
    $xml = $this-&gt;view-&gt;render('ping_technorati.phtml');

    $httpclient = new Zend_Http_Client('http://rpc.technorati.com/rpc/ping');
            $httpclient-&gt;setHeaders('User-Agent', 'PHP/Zend Framework/Zend_Http');

    $httpclient-&gt;setRawData($xml, 'text/xml')-&gt;request('POST');

    $response = $httpclient-&gt;request();

    if($response-&gt;isSuccessful() === true) {
        return true;
    } else {
        return false;
    }
}</pre>
</div>
</div></blockquote>
<p>You also need a little view in XML format like it is described in the
<a class="reference external" href="http://technorati.com/developers/ping/">Technorati Ping Configuration
Guide</a> and ready to go you
are!</p>
</div>]]></description>
            <pubDate>Sat, 17 May 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/05/07/zend-form-rapid-development-plugin-for-eclipse.html</link>
            <guid>http://www.whitewashing.de/2008/05/07/zend-form-rapid-development-plugin-for-eclipse.html</guid>
            <title><![CDATA[Zend_Form - Rapid Development Plugin for Eclipse?]]></title>
            <description><![CDATA[<div class="section" id="zend-form-rapid-development-plugin-for-eclipse">
<h1>Zend_Form - Rapid Development Plugin for Eclipse?</h1>
<p>I found some time in the last weeks to reconsider <a class="reference external" href="http://framework.zend.com">Zend
Framework</a>, this time in the 1.5 version,
for this blog software and rewrote all Forms using the new Zend_Form
component. I have to say, i love it. Its very easy using the already
existing Zend_Validate and Zend_Filter components as input for the
generated form fields. Another plus is the handling of errors in input
and re-entering/displaying text.</p>
<p>There is also a neat feature of the Zend_Form component, which allows
to <a class="reference external" href="http://framework.zend.com/manual/en/zend.form.quickstart.html#zend.form.quickstart.config">generate complete forms by passing an appropriately formatted
Zend_Config_Ini object to the Zend_Form
Constructor</a>.
So my idea was, why not program an Eclipse Plugin allowing to rapidly
generate and edit forms using a point-and-click plugin window approach,
which would ultimately generate your Form INI code.</p>
<p>This might have been a great <a class="reference external" href="http://code.google.com/soc/">Google Summer of Code
idea</a> for the Eclipse Foundation (since
Zend is not taking part).</p>
</div>]]></description>
            <pubDate>Wed, 07 May 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/30/implementing-zend-auth-acl-and-caching.html</link>
            <guid>http://www.whitewashing.de/2008/06/30/implementing-zend-auth-acl-and-caching.html</guid>
            <title><![CDATA[Implementing Zend Auth, Acl and Caching]]></title>
            <description><![CDATA[<div class="section" id="implementing-zend-auth-acl-and-caching">
<h1>Implementing Zend Auth, Acl and Caching</h1>
<p>I managed to work a bit on the blog, enabling me to have new instance in
the series, How to refactor and extend your own blog software using
<a class="reference external" href="http://framework.zend.com">Zend Framework</a>. This time: Implementing
meaningful Auth and ACL mechanisms and <a class="reference external" href="http://www.whitewashing.de/blog/articles/41">fixing view
caching</a>, which did not
work in its original implementation due to different users groups
sharing the same cached views.</p>
<p>In the last days I came across two in depth tutorials on Zend_Acl and
Zend_Auth integration to MVC. Most people probably saw the DevZone
article “<a class="reference external" href="http://devzone.zend.com/article/3509-Zend_Acl-and-MVC-Integration-Part-I-Basic-Use">Zend_Acl and MVC Integration (part
1)</a>”
by Aldemar Bernal on the Frameworks Frontpage. Another good article was
written by Frank Ruske in the latest german <a class="reference external" href="http://www.phpmagazin.de">PHP
Magazin</a> (<a class="reference external" href="http://it-republik.de/zonen/magazine/ausgaben/psfile/source_file/14/Seite_80__482a98c572a5c.zip">Zipped Source Code of the
Example</a>).
I took the best ideas of both articles and merged them into the existing
components of my blog.</p>
<p>This now enables me to cache the site depending on the Auth status of
the page user agent. The blog is now caching all views that are
generated for guest users. Since there is no “registered” or “member”
account yet, this means the blogs content is cached and served from
cache for everyone except me when I am logged in. To get this work I
added some simple additional check in <a class="reference external" href="http://devzone.zend.com/article/3372-Front-Controller-Plugins-in-Zend-Framework">Matthews Cache View Controller
Plugin</a>:</p>
<blockquote>
<div><div class="highlight-python"><pre>public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
    $auth = Zend_Auth::getInstance();
    if($auth-&gt;hasIdentity()) {
        self::$doNotCache = true;
        return;
    }
    [..]
}</pre>
</div>
</div></blockquote>
<p>This prevents caching for registered identities.</p>
</div>]]></description>
            <pubDate>Mon, 30 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/14/exim4-and-virtual-users-forward-files.html</link>
            <guid>http://www.whitewashing.de/2008/06/14/exim4-and-virtual-users-forward-files.html</guid>
            <title><![CDATA[Exim4 and Virtual Users .forward Files]]></title>
            <description><![CDATA[<div class="section" id="exim4-and-virtual-users-forward-files">
<h1>Exim4 and Virtual Users .forward Files</h1>
<p>Some days ago I began to wonder why some mails in mail account were
filtered by Exims .forward file why some are not. It took until today
that I found out what was the problem and how to fix it.</p>
<p>I implemented a virtual users/domains system for Exim using several
different documentations and tutorials. Right now some parts of my
system include the documentation on</p>
<p><a class="reference external" href="http://www.tty1.net/virtual_domains_en.html">http://www.tty1.net/virtual_domains_en.html</a></p>
<p>Now the problem is that the userforward router is only working for
accounts whose $local_part is an existing system user. I came up with
the following additional router that solves the problem. Its written for
the MySQL table layout that is specified in the Tutorial above.</p>
<blockquote>
<div><div class="highlight-python"><pre>virtualuserforward:
  debug_print = &quot;R: virtualuserforward for $local_part@$domain&quot;
  driver = redirect
  domains = +local_domains
  file = ${lookup mysql{SELECT CONCAT(home,'.forward') AS forward FROM users \
        WHERE id='${quote_mysql:$local_part}@${quote_mysql:$domain}'}}
  no_verify
  no_expn
  check_ancestor
  directory_transport = address_directory
  file_transport = address_file
  pipe_transport = address_pipe
  reply_transport = address_reply
  allow_filter

  user = ${lookup mysql{SELECT uid FROM users \
        WHERE id='${quote_mysql:$local_part}@${quote_mysql:$domain}'}}
  group = ${lookup mysql{SELECT gid FROM users \
        WHERE id = '${quote_mysql:$local_part}@${quote_mysql:$domain}'}}</pre>
</div>
</div></blockquote>
<p>Now each virtual user is using the .forward file in its actual system
user account home directory. The next problem was: $home is not defined
in this case in the .forward file syntax: Its empty. So replacing $home
with its obvious path leads to the final solution.</p>
</div>]]></description>
            <pubDate>Sat, 14 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/25/multimediatreff-on-frameworks.html</link>
            <guid>http://www.whitewashing.de/2008/06/25/multimediatreff-on-frameworks.html</guid>
            <title><![CDATA[Multimediatreff on Frameworks]]></title>
            <description><![CDATA[<div class="section" id="multimediatreff-on-frameworks">
<h1>Multimediatreff on Frameworks</h1>
<p>My neighbour gladly called my attention to the
<a class="reference external" href="http://www.multimediatreff.de">Multimediatreff</a>, a relaxed conference
that is held about three times a year, this last saturday on the topic:
Frameworks and Content-Management-Systems.</p>
<p>It was held in a very nice conference center in cologne, and from what I
heard about 200 people attended. The first two topics were on
<a class="reference external" href="http://www.joomla.org/">Joomla!</a> and barrier-free
<a class="reference external" href="http://www.typo3.org">Typo3</a>. Since I am more the framework guy, I
did not enjoy them too much. At least I got some input on how a
barrier-free website has to function. The Joomla! presentation supported
my prejudice, that programming in and for Joomla! produces ugly code.</p>
<p>I did like the presentations on frameworks, the most interesting being
the <a class="reference external" href="http://www.cakephp.org">CakePHP</a> presentation by <a class="reference external" href="http://teemow.com/">Timo
Derstappen</a>, since I haven’t looked into Cake for
about one and a half years. I have seen that with the new to come
version 2, the framework became even better, now supporting easy code
generation and flexible site generation. But its still somehow a Ruby
clone and forces me too much in my programming style.</p>
<p>The <a class="reference external" href="http://framework.zend.com">Zend Framework</a> presentation was done
by Carsten Möhrke, who also wrote the first german ZF Book. He showed
the creation of a blog using Zend Framework, being the Hello World
example for frameworks. He specifically showed, that you can use
anything you want as a model, a Zend_Db_Table object or any other
object. He also showed something like a Data-Mapper pattern in his
application. I got some ideas from this I probably will write about some
later time.</p>
<p>I also enjoyed the <a class="reference external" href="http://www.rubyonrails.de">Rails</a> presentation,
because I never got the chance to look the Ruby guys at work of the
shoulder. But this is even worse than CakePHP was my first observation.
I am no fan of ActiveRecord being forced upon you as Model
implementation.</p>
<p>The pizza battle, mysteriously announced by the host, was another
highlight, as well as the drinks and snacks in between. All in all I can
highly recommend the Multimediatreff for the next time.</p>
</div>]]></description>
            <pubDate>Wed, 25 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/22/zf-caching-pages-via-front-controller-plugin.html</link>
            <guid>http://www.whitewashing.de/2008/06/22/zf-caching-pages-via-front-controller-plugin.html</guid>
            <title><![CDATA[ZF: Caching Pages via Front Controller Plugin]]></title>
            <description><![CDATA[<div class="section" id="zf-caching-pages-via-front-controller-plugin">
<h1>ZF: Caching Pages via Front Controller Plugin</h1>
<p>Today I implemented caching using a front controller plugin (<a class="reference external" href="http://devzone.zend.com/article/3372">see
Matthews post on Zend Devzone</a>)
into the Whitewashing blog software via Zend_Cache and the Filesystem
Backend. I ran some superficial Apache Benchmark tests to have a look
at the gain change in performance.</p>
<p>First of all i used the complete Plugin from <a class="reference external" href="http://devzone.zend.com/article/3372">Matthews article on Zend
Devzone</a> and a missing function
getCache() in the code fragment:</p>
<blockquote>
<div><div class="highlight-python"><pre>public function getCache()
{
    if( ($response = $this-&gt;cache-&gt;load($this-&gt;key)) != false) {
        return $response;
    }
    return false;
}</pre>
</div>
</div></blockquote>
<p>I loaded the Plugin into the front controller and initialized it with a
Zend_Config_Ini object. This all works very smoothly and caching is
ready to begin.</p>
<p>Testing came to the result that with 1000 requests, 10 of them concurrent
(ab -n 1000 -c 10), which I know is a rather unrealistic assumption for
this blog, the request time dropped by half, from six to three seconds
(still lot of time, but this isn’t the best webserver).</p>
<div class="section" id="results-without-caching">
<h2>Results without caching</h2>
<div class="highlight-python"><pre>Requests per second:    1.49 [#/sec] (mean)
Time per request:       6695.213 [ms] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       26   30   4.0     30      43
Processing:  1556 6452 3372.1   5511   14768
Waiting:     1436 6129 3174.1   5145   14595
Total:       1583 6483 3373.2   5538   14810</pre>
</div>
</div>
<div class="section" id="results-with-caching">
<h2>Results with caching</h2>
<div class="highlight-python"><pre>Requests per second:    3.03 [#/sec] (mean)
Time per request:       3304.534 [ms] (mean)

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       26   31   6.3     30      73
Processing:   781 3214 1757.7   3103    7445
Waiting:      650 3055 1731.4   2928    7190
Total:        809 3245 1757.8   3135    7475</pre>
</div>
<p>As said before this testing is superficial, but its gives a broad sense
of what performance gain is possible with just some lines of code and a
temporary directory. Using memcache will probably speed up the process
another good amount.</p>
<p>Later I realized that complete page caching (rather than block element
caching) sucks when you inject admin area links into the navigation,
which would allow non-logged in users to see parts of the admin area so
I had to disable caching totally. You never know in the first place (you
should though). I have to rework my admin area or extend my
authentication or the caching plugin somehow. This will probably be the
topic another time.</p>
</div>
</div>]]></description>
            <pubDate>Sun, 22 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/21/on-frameworks-and-javascript-coupling.html</link>
            <guid>http://www.whitewashing.de/2008/06/21/on-frameworks-and-javascript-coupling.html</guid>
            <title><![CDATA[On Frameworks and Javascript Coupling]]></title>
            <description><![CDATA[<div class="section" id="on-frameworks-and-javascript-coupling">
<h1>On Frameworks and Javascript Coupling</h1>
<p><a class="reference external" href="http://www.zend.com">Zend</a> announced they work together with the
<a class="reference external" href="http://www.dojotoolkit.org">Dojo Team</a> to integrate Javascript
support into the Zend Framework. What this actually means is that you
can write your Javascript Code in PHP if you’re javascript library of
choice is Dojo.</p>
<p>Since Dojo is not my library of choice I would have to write a JQuery
View Helper on my own or wait until somebody else releases one.</p>
<p>But why not write javascript? Its very easy with all those libraries and
addresses most cross browser incompatibilities: <a class="reference external" href="http://www.b-list.org/weblog/2006/jul/02/django-and-ajax/">One
Django</a>,
<a class="reference external" href="http://www.builtfromsource.com/2006/12/20/does-ajax-have-a-place-in-the-application-framework/">one Zend Framework
developer</a>
argue framework and javascript coupling is not the way to go based on
the arguments that its breaks the MVC pattern, leads to function calls
equal to those in javascript in its framework respective language, and
that javascript is actually something any good webdeveloper should be
able to program, even when its just using library components.</p>
<p>Using <a class="reference external" href="http://jquery.com">JQuery</a> without any help from tools for
about a year now I can say there are still those days where javascript
drives me mad, but most of the time I its working perfect. Since Ajax
related calls like GET, POST, and FORM stuff are oneliners I don’t see
why one would need tighter integration of JS and frameworks.</p>
<p>Larger Javascript components like Popup Calendars, Autocomplete and the
like are harder to integrate than in Rails or cakePHP, but thinking
about the problem a little longer leads to powerful reusable solutions,
that save time on integration after the first initial setup.</p>
</div>]]></description>
            <pubDate>Sat, 21 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/21/simplifying-zf-scope-of-variables-in-view-and-controller.html</link>
            <guid>http://www.whitewashing.de/2008/06/21/simplifying-zf-scope-of-variables-in-view-and-controller.html</guid>
            <title><![CDATA[Simplifying ZF: Scope of Variables in View and Controller]]></title>
            <description><![CDATA[<div class="section" id="simplifying-zf-scope-of-variables-in-view-and-controller">
<h1>Simplifying ZF: Scope of Variables in View and Controller</h1>
<p>As a follow up on the <a class="reference external" href="http://destiney.com/blog/zend-framework-web-2-0-framework-my-ass">Zend Framework, “Web 2.0 Framework” My
Ass!</a>
article referenced earlier I came up with some simplifications of the Zend
View and Controller variable coupling.</p>
<p>Using some code in the article I created a new Zend_View_Extended
class which offers the possibility to circumvent the access of variables
via $this and directly registers each variable key of the Zend_View
object as an own variable in the script template:</p>
<blockquote>
<div><div class="highlight-python"><pre>class Zend_View_Extended extends Zend_View_Abstract
{
    protected function _run()
    {
        while( list( $k, $v ) = each( $this ) ) ${$k} = $v;

        include func_get_arg(0);
    }
}</pre>
</div>
</div></blockquote>
<p>Now rather than calling $this-&gt;data you can call $data in a script
template. Of course this comes with additional overhead of each variable
being registered twice. I don’t know how this handles performance wise,
but maybe unsetting $this variables after copying solves this. Also you
have to overwrite the initView() method of your base Controller Action
class.</p>
<p>Another simplification would be to allow for the following direct
variable settings in any Controller Action, which would shorten the
$this-&gt;view-&gt;variable call, to derive the same functionality via
$this-&gt;variable. I haven’t tested this though.</p>
<blockquote>
<div><div class="highlight-python"><pre>class Zend_Controller_SimpleAction extends Zend_Controller_Action
{
    function __set($name, $value)
    {
        $this-&gt;view-&gt;{$name} = $value;
    }
}</pre>
</div>
</div></blockquote>
</div>]]></description>
            <pubDate>Sat, 21 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/06/24/teaching-zend-form-some-mvc.html</link>
            <guid>http://www.whitewashing.de/2008/06/24/teaching-zend-form-some-mvc.html</guid>
            <title><![CDATA[Teaching Zend_Form some MVC]]></title>
            <description><![CDATA[<div class="section" id="teaching-zend-form-some-mvc">
<h1>Teaching Zend_Form some MVC</h1>
<p>Lots of people complain that Zend Form runs counter to the MVC spirit,
because it handles validation, business logic and view elements all in
one acting as Model, Controller and View.</p>
<p>Extending the Zend Form component to handle all this different aspects
in different layers of the application is rather easy though. What we
want of a MVC compatible Form object is the following:</p>
<ul class="simple">
<li>The <strong>model</strong> escapes and validates all the data that is put into the
form.</li>
<li>The <strong>view</strong> decides on how the form is displayed.</li>
<li>The <strong>controller</strong> moves data from the model to the view and back,
handling the stages of the form request.</li>
</ul>
<p>The first step is, <strong>allowing any Model that implements
Zend_Validator_Interface to hook into the Zend_Form Validation
process</strong>. We generate a new class, WW_Form_Mvc and allow a function
setModel() to insert any Model object that implements
Zend_Validator_Interface into the form. We extend isValid(),
getMessages() and getErrors() to not only check all the form elements
validators, but also the models validators. Please note that the
array_merge() solution is not the correct way of how this snippet
should work. Any merge operation of the messages and errors has to be on
a field key level, which is not currently done.</p>
<blockquote>
<div><div class="highlight-python"><pre>class WW_Form_Mvc extends Zend_Form
{
    protected $model = null;

    /**
     * Extends isValid() method of Zend Form to check for validity of specified model
     * @param Array $data
     * @return Boolean
     */
    public function isValid($data)
    {
        $valid = parent::isValid($data);

        if($valid == true &amp;&amp; !is_null($model)) {
            $valid = $this-&gt;model-&gt;isValid($data) &amp;&amp; $valid;
        }
        return $valid;
    }

    /**
     * Extends getMessages() Validator Interface implementation of Zend Form to also
     * return the messages of the Model validation.
     * @return Array
     */
    public function getMessages($name = null, $suppressArrayNotation = false)
    {
        $messages = parent::getMessages($name, $suppressArrayNotation);

        if(!is_null($model)) {
             $form_messages = $this-&gt;model-&gt;getMessages();

             $messages = array_merge($messages, $form_messages);
        }

        return $messages;
    }

    /**
     * Extends getErrors() Validator Interface implementation of Zend Form to also
     * return the errors of the Model validation.
     * @return Array
     */
    public function getErrors($name = null)
    {
         $messages = parent::getErrors($name);

        if(!is_null($model)) {
             $form_messages = $this-&gt;model-&gt;getErrors();

             $messages = array_merge($messages, $form_messages);
        }

        return $messages;
    }

    /**
     * Set a Model object, which has to implement Zend_Validate_Interface
     * @throws Zend_Exception
     */
    public function setModel($model)
    {
        if($model instanceof Zend_Validate_Interface) {
            $this-&gt;model = $model;
        } else {
             throw new Zend_Exception('WW_Form_Mvc expects a model of type Zend_Validate_Interface');
        }
    }
}</pre>
</div>
<p>We then extend the WW_Form_Mvc class to disable the automatic
loading of decorators in the Constructor and additionally allow to
pass a Model to the constructor as second argument:</p>
<blockquote>
<div><div class="highlight-python"><pre>class WW_Form_Mvc
{
    protected $model = null;

    /**
     * this overrides the original Zend_Form Constructor and skips
     * the decorator initialisation, because this is now being handled
     * by View Helpers
     */
    public function __construct($options=null, $model=null)
    {
        if (is_array($options)) {
            $this-&gt;setOptions($options);
        } elseif ($options instanceof Zend_Config) {
            $this-&gt;setConfig($options);
        }

        // Extensions...
        $this-&gt;init();

        if(!is_null($model)) {
             $this-&gt;setModel($model);
        }
    }

    // All the other stuff here
}</pre>
</div>
</div></blockquote>
<p>In our views we want to <strong>use helper methods to manage the
displaying of the form</strong>. For each different style of form
displaying, we can generate different helpers. For example a helper
that would only apply the default decorators would look like this:</p>
<blockquote>
<div><div class="highlight-python"><pre>class WW_View_Helper_FormDefault
{
    /**
     * Load only default decorators on this Zend_Form object
     *
     * @param Zend_Form $form
     */
    public function formDefault(Zend_Form $form)
    {
        if($form instanceof Zend_Form) {
            $form-&gt;loadDefaultDecorators();
            return $form;
        }
    }
}</pre>
</div>
</div></blockquote>
<p>We can now use this helper and in any template say: &lt;?=
$this-&gt;formDefault($this-&gt;someForm); ?&gt; We can now look at our
controller action that implements this form and we will see that it
does not look different from what we would have done before:</p>
<blockquote>
<div><div class="highlight-python"><pre>function formAction()
{
    $model = new SomeModel();

    $form = new WW_Form_Mvc();
    $form-&gt;setModel($model);

    // generate form here, adding elements and stuff

    if($form-&gt;isValid($_POST)) {
        $model-&gt;insert($form-&gt;getValues());
        $this-&gt;view-&gt;form = &quot;Form was submitted!&quot;;
    } else {
        $this-&gt;view-&gt;form = $form;
    }
}</pre>
</div>
</div></blockquote>
<p>Isnt that nice? Now each part of the equation is doing what its
supposed to do.</p>
</div></blockquote>
</div>]]></description>
            <pubDate>Tue, 24 Jun 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/05/overwrite-ezcmvccontroller-a-bit-more-rapid.html</link>
            <guid>http://www.whitewashing.de/2008/11/05/overwrite-ezcmvccontroller-a-bit-more-rapid.html</guid>
            <title><![CDATA[Overwrite ezcMvcController - A bit more rapid]]></title>
            <description><![CDATA[<div class="section" id="overwrite-ezcmvccontroller-a-bit-more-rapid">
<h1>Overwrite ezcMvcController - A bit more rapid</h1>
<p>ezComponents gets Mvc in its 2008.2 version. I have played around a bit
with the alpha version, since I am currently searching for a good
framework for a high performance application. My first benchmarks on
ezcMvc just say: wh000pie! A lot faster as compared to the Zend
Framework.
Still ezcMvc is VERY loosely coupled and you have to write lots of lines
to get where ZF gets you with less (more magic involved). As you can see
from the <a class="reference external" href="http://ezcomponents.org/docs/tutorials/MvcTools#creating-the-controller">tutorial on the ezcMvcTools
component</a>
it is currently a bit unwieldily to work with ezcMvcController since you
have to create and return result objects everywhere. This is very nice
since it abstracts from the actual response type (could be www, mail,
cli, anything).
I have created a very little extension of the ezcMvcController class
that hopefully serves you quite some time. You can append variables to
the ezcMvcResult object by calling the magic __get and __set on the
controller. Plus it offers a method to use the ezcMvcInternalRedirect
instead of the result. See for yourself:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myController extends ezcMvcController
{
    protected $result;

    public function createResult()
    {
        $actionMethod = $this-&gt;createActionMethodName();

        if ( method_exists( $this, $actionMethod ) ) {
            $status = $this-&gt;$actionMethod();
            if($status != 0) {
                $this-&gt;getResult()-&gt;status = $status;
            }
            return $this-&gt;getResult();
        } else {
            throw new ezcMvcActionNotFoundException( $this-&gt;action );
        }
    }

    protected function _redirect($uri)
    {
        $request = clone $this-&gt;request;
        $request-&gt;uri = $uri;
        $this-&gt;result = new ezcMvcInternalRedirect($request);
    }

    public function __get($name)
    {
        if(isset($this-&gt;getResult()-&gt;variables[$name])) {
            return $this-&gt;getResult()-&gt;variables[$name];
        }
        return null;
    }

    public function __set($name, $value)
    {
        $this-&gt;getResult()-&gt;variables[$name] = $value;
    }

    public function __isset($name)
    {
        return isset($this-&gt;getResult()-&gt;variables[$name]);
    }

    protected function getResult()
    {
        if($this-&gt;result === null) {
            $this-&gt;result = new ezcMvcResult();
        }
        return $this-&gt;result;
    }
}</pre>
</div>
</div></blockquote>
<p>You can now use a controller in the following way:</p>
<blockquote>
<div><div class="highlight-python"><pre>class dashboardController extends myController
{
    public function doIndex()
    {
        $this-&gt;cookie = &quot;Cookie!&quot;; // Proxy to $ezcMvcResult-&gt;variables['cookie']
    }

    public function doRedirect()
    {
        $this-&gt;_redirect(&quot;/&quot;);
    }
}</pre>
</div>
</div></blockquote>
<p>Very nice! The next thing I have to extend in ezcMvc is automagical
matching of controller and action names to view output names with a
special View Handler that takes care of this. This saves another bunch
of work you have to cope with in the current standard setup.</p>
</div>]]></description>
            <pubDate>Wed, 05 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/25/next-zf-mini-release-1-7-1.html</link>
            <guid>http://www.whitewashing.de/2008/11/25/next-zf-mini-release-1-7-1.html</guid>
            <title><![CDATA[Next ZF Mini Release: 1.7.1]]></title>
            <description><![CDATA[<div class="section" id="next-zf-mini-release-1-7-1">
<h1>Next ZF Mini Release: 1.7.1</h1>
<p>In the next days the next mini release of the Zend Framework will be
released and I want to keep you up to date of my progress on it.
I got lots of feedback on the jQuery component and also had the
possibility to fix some bugs and documentation issues. I also fixed some
minor bugs that have been in the Zend_Soap_Wsdl stuff i added for the
1.7 release.
And a question for the 1.8 release that is due around February 2009:
What do you think is missing in the jQuery support to ZF? Any widgets or
stuff that you want to have included?</p>
</div>]]></description>
            <pubDate>Tue, 25 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/01/zf-1-7-jquery-is-in-zend-soap-with-lots-of-bugfixes.html</link>
            <guid>http://www.whitewashing.de/2008/11/01/zf-1-7-jquery-is-in-zend-soap-with-lots-of-bugfixes.html</guid>
            <title><![CDATA[ZF 1.7: jQuery is in! Zend_Soap with lots of Bugfixes.]]></title>
            <description><![CDATA[<div class="section" id="zf-1-7-jquery-is-in-zend-soap-with-lots-of-bugfixes">
<h1>ZF 1.7: jQuery is in! Zend_Soap with lots of Bugfixes.</h1>
<p>The next version of <a class="reference external" href="http://framework.zend.com">Zend Framework</a> will
appear quite soon (16th November) and there will be lots of buzz about
Zend Amf, the new component sponsored by Adobe to support Adobe Flash
(or other tools) to PHP communications.</p>
<p>Besides the buzz there is some stuff from me getting into the Zend
Framework. jQuery View and Form Helpers will allow you to throw the Dojo
stuff away and use the great jQuery. This is of course inherently
subjective, but still different opportunities are always great.</p>
<p>Additionally I have been fixing quite some bugs on the Zend Soap
component and will manage to fix further stuff until the 1.7 release I
hope. This will make especially Wsdl and AutoDiscover produce valid WSDL
XML plus adds setObject() support to Zend_Soap_Server.</p>
<p>You can now choose between several strategies to evaluate complex types
in WSDL Autodiscovering. Array of Datatypes (simple or complex) via
type[] syntax and complex objects can be parsed differently now based on
settings.</p>
</div>]]></description>
            <pubDate>Sat, 01 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/01/performance-in-calypso-and-bugs.html</link>
            <guid>http://www.whitewashing.de/2008/11/01/performance-in-calypso-and-bugs.html</guid>
            <title><![CDATA[Performance in Calypso (and Bugs)]]></title>
            <description><![CDATA[<div class="section" id="performance-in-calypso-and-bugs">
<h1>Performance in Calypso (and Bugs)</h1>
<p>I have tested Calypso performance some weeks ago and have not been able
to write on it before. Don’t use it please its fucking slow and cannot
be optimized in the current architecture, because the template will NOT
be parsed into intermediate PHP code.</p>
<p>Additionally there are some bugs:</p>
<ol class="arabic simple">
<li>You cannot currently use UTF8 encoding since htmlentities deep in the
escape mechanism cannot be given the utf-8 specification.</li>
<li>Triple or higher inheritance may not work under some circumstances.
Which sucks.</li>
</ol>
<p>I sadly have no time currently to fix any of the issues poping up with
Calypso, so please don’t use it for anything production.</p>
</div>]]></description>
            <pubDate>Sat, 01 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/29/encouraging-forks-for-calypso-dtl.html</link>
            <guid>http://www.whitewashing.de/2008/11/29/encouraging-forks-for-calypso-dtl.html</guid>
            <title><![CDATA[Encouraging forks for Calypso DTL]]></title>
            <description><![CDATA[<div class="section" id="encouraging-forks-for-calypso-dtl">
<h1>Encouraging forks for Calypso DTL</h1>
<p>I still get a bunch of emails regarding the <a class="reference external" href="http://www.beberlei.de/calypso">Calypso DTL template
engine</a> that I have written some month
ago and which i can currently not maintain any further (<a class="reference external" href="http://www.whitewashing.de/blog/articles/86">see my posting
on that</a>). Still I
encourage anyone to fork the project and develop it further. Personally
what I think is missing are some bugfixes and enhancements regarding the
compiling and parsing. I created a <a class="reference external" href="http://github.com/beberlei/calypsodtl/tree/master">GITHub Project for Calypso
DTL</a>, so
collaborative development is very easy and added general TODOS to the
README.txt that is on the front page of github project page.</p>
</div>]]></description>
            <pubDate>Sat, 29 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/11/12/updating-from-kde3-5-to-kde4-with-mac-style-menubars.html</link>
            <guid>http://www.whitewashing.de/2008/11/12/updating-from-kde3-5-to-kde4-with-mac-style-menubars.html</guid>
            <title><![CDATA[Updating from KDE3.5 to KDE4 with Mac-Style Menubars]]></title>
            <description><![CDATA[<div class="section" id="updating-from-kde3-5-to-kde4-with-mac-style-menubars">
<h1>Updating from KDE3.5 to KDE4 with Mac-Style Menubars</h1>
<p>It seems KDE4 has no Mac-Style menubars and when you upgrade from 3.5 to
4.1 within the same config folder (say you use the kubuntu distribution
upgrade installer like I did) you end up with no menubars at all.
To solve this little issue find a variable “macStyle = true” in the
/home/username/.kde/share/config/kdeglobals file and switch it to
macStyle = false and you have your menubars back.</p>
</div>]]></description>
            <pubDate>Wed, 12 Nov 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/02/dojox-django-template-language-example-with-data-from-php-json.html</link>
            <guid>http://www.whitewashing.de/2008/08/02/dojox-django-template-language-example-with-data-from-php-json.html</guid>
            <title><![CDATA[DojoX Django Template Language Example with Data from PHP/JSON]]></title>
            <description><![CDATA[<div class="section" id="dojox-django-template-language-example-with-data-from-php-json">
<h1>DojoX Django Template Language Example with Data from PHP/JSON</h1>
<p>This is a simple example how you would use DojoX Django Template
Language component filled with data from a JSON GET Response:</p>
<blockquote>
<div><div class="highlight-python"><pre>&lt;script type=&quot;text/javascript&quot; src=&quot;/development/dojo-release-1.1.1/dojo/dojo.js&quot; djConfig=&quot;parseOnLoad:true, isDebug:true&quot;&gt;&lt;/script&gt;

&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&gt;&lt;!--
dojo.require(&quot;dojox.dtl&quot;);
dojo.require(&quot;dojox.dtl.Context&quot;);
dojo.require(&quot;dojox.dtl.ext-dojo.NodeList&quot;);
dojo.addOnLoad(
    dojo.xhrGet({url: &quot;dojotest.php&quot;, handleAs: &quot;json&quot;, handle: function(data,ioArgs){
        if(typeof data == &quot;error&quot;){
            console.log(&quot;error?&quot;,data);
        } else {
            dojo.query(&quot;#test&quot;).dtl(&quot;I am eating {{food.fruit}} and {{food.meat}}&quot;, data);
        }
    }
}));
--&gt;&lt;/script&gt;

::

    &lt;?php
    header('Content-type: text/json');
    $food = array('food' =&gt; array('fruit' =&gt; 'apple', 'meat' =&gt; 'chicken'));
    echo json_encode($food);
    ?&gt;</pre>
</div>
</div></blockquote>
</div>]]></description>
            <pubDate>Sat, 02 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/02/wrestling-with-dojo.html</link>
            <guid>http://www.whitewashing.de/2008/08/02/wrestling-with-dojo.html</guid>
            <title><![CDATA[Wrestling with Dojo]]></title>
            <description><![CDATA[<div class="section" id="wrestling-with-dojo">
<h1>Wrestling with Dojo</h1>
<p>I have to complain about the <a class="reference external" href="http://www.dojotoolkit.org">Dojo
Toolkit</a> (Considering the <a class="reference external" href="http://www.whitewashing.de/blog/articles/50">project I am
using this for</a>). It has
the worst documentation and API guides I have ever seen. The
documentation (called the Dojo Book) has an unnecessary complex
structure to click through and its contents are wrapped around examples
that are so overly complex that you click away the pages when they get
smashed at your head.</p>
<p>The API too, has no clear structure and hides its contents behind
cryptic names such as “dnd”, “fx”, “rpc”. Descriptions of the functions
sum to very small sentences and additional options are listed without
any description at all other than a link to where they are defined in
the project. There are no short examples given to any function like
<a class="reference external" href="http://www.jquery.com">jQuery</a> does.</p>
<p>In general I think the Dojos Site is too complex and hard to navigate.
The layout seems to change massively on each click and you it is hard
recognize common patterns. Dear Dojo Team, please make your project more
accessible!</p>
</div>]]></description>
            <pubDate>Sat, 02 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/08/first-impressions-on-zend-soap-and-a-basic-implementation.html</link>
            <guid>http://www.whitewashing.de/2008/08/08/first-impressions-on-zend-soap-and-a-basic-implementation.html</guid>
            <title><![CDATA[First impressions on Zend_Soap and a basic implementation]]></title>
            <description><![CDATA[<div class="section" id="first-impressions-on-zend-soap-and-a-basic-implementation">
<h1>First impressions on Zend_Soap and a basic implementation</h1>
<p>The <a class="reference external" href="http://framework.zend.com">Zend Framework</a> release candidate for
version 1.6 includes a new component for SOAP operations.
<a class="reference external" href="http://framework.zend.com/manual/en/zend.soap.html">Zend_Soap_Server/Client</a>
extend the PHP functionality of the SOAPClient and SOAPServer objects,
which by itself is trivial. The more important functionality it ads to
the package is the <a class="reference external" href="http://framework.zend.com/manual/en/zend.soap.autodiscovery.introduction.html">AutoDiscovery
Component</a>.</p>
<p>Generally you can use <a class="reference external" href="http://en.wikipedia.org/wiki/SOAP">SOAP</a> in the
so called “non-wsdl” mode, that is if you specify the correct options
like the soap service location and uri, you don’t need any description
of the service for the clients. This is only useful if you’re using the
SOAP Service internally since you then know about all the available
functions and methods. If you want to offer the Service for external
users you want to use the WSDL-mode: Generate a
<a class="reference external" href="http://en.wikipedia.org/wiki/Web_Services_Description_Language">WSDL</a>
that describes the services available methods, their parameters and
return types is an important task.</p>
<p>Using Zend_Soap_AutoDiscover you can generate your WSDL file
automatically by reflecting on the given Service Class methods. This
works as follows. We setup a simple service:</p>
<blockquote>
<div><div class="highlight-python"><pre>class HelloWorldService
{
    /**
     * @return string
     */
    public function helloWorld()
    {
        return &quot;Hello World!&quot;;
    }

    /**
     * @return array
     */
    public function getFruits()
    {
        return array('apple', 'orange', 'banana');
    }
}</pre>
</div>
</div></blockquote>
<p>It is important that you specify the Doc Comments @param and @return
otherwise the AutoDiscovery of the correct parameter and return types
cannot be resolved. We will now setup a simple SOAP Server access point,
that will also generate our WSDL file for description of this HelloWorld
service:</p>
<blockquote>
<div><div class="highlight-python"><pre>require_once &quot;HelloWorldService.php&quot;;
require_once &quot;Zend/Soap/Server.php&quot;;
require_once &quot;Zend/Soap/AutoDiscover.php&quot;;

if(isset($_GET['wsdl'])) {
    $autodiscover = new Zend_Soap_AutoDiscover();
    $autodiscover-&gt;setClass('HelloWorldService');
    $autodiscover-&gt;handle();
} else {

    $soap = new Zend_Soap_Server(&quot;http://localhost/soapserver.php?wsdl&quot;); // this current file here
    $soap-&gt;setClass('HelloWorldService');
    $soap-&gt;handle();
}</pre>
</div>
</div></blockquote>
<p>Now we have our SOAP Service up and running and any client can access
the HelloWorldService class from a remote or local location with just
this simple lines:</p>
<blockquote>
<div><div class="highlight-python"><pre>require_once &quot;Zend/Exception.php&quot;;
require_once &quot;Zend/Soap/Client.php&quot;;

try {
    $client = new Zend_Soap_Client(&quot;http://localhost/soapserver.php?wsdl&quot;); // Servers WSDL Location
    $string =  $client-&gt;helloWorld();
    $fruits = $client-&gt;getFruits();

    var_dump($string);
    var_dump($fruits);
} catch(Zend_Exception $e) {
    echo $e-&gt;getMessage();
}</pre>
</div>
<p>This is easy. Additionally Zend_Soap offers a WSDL class to
generate your own WSDL file based on your special preferences, which
is a nice feature. I guess only some people can write a correct WSDL
XML specification file on their own from scratch, so using a
powerful helper is reasonable.</p>
<p>The usage of Zend_Soap is quite simple and straightforward as is
PHP5’s internal SOAP Service and might therefore gain widespread
use. I have never tested PEAR’s WSDL Autodiscovery, so i cannot draw
comparisons.</p>
</div></blockquote>
</div>]]></description>
            <pubDate>Fri, 08 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/22/zend-helper-for-jquery-ui-widgets-demo.html</link>
            <guid>http://www.whitewashing.de/2008/08/22/zend-helper-for-jquery-ui-widgets-demo.html</guid>
            <title><![CDATA[Zend Helper for jQuery UI Widgets Demo]]></title>
            <description><![CDATA[<div class="section" id="zend-helper-for-jquery-ui-widgets-demo">
<h1>Zend Helper for jQuery UI Widgets Demo</h1>
<p>I finished <a class="reference external" href="http://www.beberlei.de/jquery/demo">a pretty demo</a> for all
the <a class="reference external" href="http://ui.jquery.com">jQuery UI widgets</a> view helpers for my
<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery+UI+Widgets+Extension+-+Benjamin+Eberlei">Zend Framework
proposal</a>.
It utilizes the <a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery_View_Helper_JQuery+-+Benjamin+Eberlei">jQuery View
helper</a>
which is <a class="reference external" href="http://www.whitewashing.de/blog/articles/67">further down the proposal
road</a>. You can have a
look at how nicely the Javascript is generated for the different jQuery
UI Widgets. A further demo showing functionality of the form decorators
and elements will follow when I finished these components.</p>
<p><strong>Update:</strong> I also added a demo showing the form elements usage I have
just finished in their first versions. I committed the classes to <a class="reference external" href="http://www.beberlei.de/dev/svn/ZendX_JQuery">the
SVN</a> so you can already
check them if you want.</p>
</div>]]></description>
            <pubDate>Fri, 22 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/28/benchmark-and-optimize-zend-framework-performance.html</link>
            <guid>http://www.whitewashing.de/2008/08/28/benchmark-and-optimize-zend-framework-performance.html</guid>
            <title><![CDATA[Benchmark and Optimize Zend Framework Performance]]></title>
            <description><![CDATA[<div class="section" id="benchmark-and-optimize-zend-framework-performance">
<h1>Benchmark and Optimize Zend Framework Performance</h1>
<p>In the fall of <a class="reference external" href="http://talks.php.net/show/froscon08">Rasmus presentation (Simple is
Hard)</a> on
<a class="reference external" href="http://www.froscon.org">FrOSCon</a> I tried to optimize <a class="reference external" href="http://framework.zend.com">Zend
Frameworks</a> performance a little bit. There
has also been a little discussion on the Zend Framework Mailing List on
this topic.</p>
<p>I haven’t changed great parts of the code or anything, I just
benchmarked how different global include strategies affect the overall
performance of my blog software written with help of the ZF. The
following include strategies were tested (I’ve used the Zend Framework
1.6 RC2 package for all of them):</p>
<ol class="arabic simple">
<li>Zend_Loader Autoload, Default PHP Include Path</li>
<li>Zend_Loader Autoload, Swapped Include Path</li>
<li>ZF 1.6 RC2 stripped from all <strong>“require_once”</strong> dependencies,
Zend_Loader Autoload, Swapped Include Path</li>
<li>ZF 1.6 RC2 stripped from all <strong>“require_once”</strong> dependencies, no
autoload, used <a class="reference external" href="http://pecl.php.net/package/inclued">inclued</a> to
find file dependencies and require (not _once) them all on startup.</li>
</ol>
<p>To strip all the require_once from the Zend Framework source code, i
built a little script to do that for me. For the last test I wrote a
little script that used the <strong>inclued_get_data()</strong> function to built a
correct dependency tree for all includes. I have put each configuration
of my Zend Framework install 30 seconds under siege with 5 concurrent
requests. I have rerun all tests with APC and without APC.</p>
<div class="section" id="results-without-apc">
<h2>Results without APC</h2>
<table border="1" class="docutils">
<colgroup>
<col width="42%"/>
<col width="21%"/>
<col width="16%"/>
<col width="21%"/>
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td>Include Strategy</td>
<td>Response time</td>
<td>Trans/sec</td>
<td>Performance %</td>
</tr>
<tr class="row-even"><td>Autoload, default include path</td>
<td>0.20</td>
<td>24.65</td>
<td>100%</td>
</tr>
<tr class="row-odd"><td>Autoload, swapped include path</td>
<td>0.19</td>
<td>26.83</td>
<td>95%</td>
</tr>
<tr class="row-even"><td>Autoload, ZF w/o require_once</td>
<td>0.17</td>
<td>29.27</td>
<td>85%</td>
</tr>
<tr class="row-odd"><td>No-Autoload, require up front</td>
<td>0.16</td>
<td>31.82</td>
<td>80%</td>
</tr>
</tbody>
</table>
<p>You can see that each step makes a ZF application run faster and that
the full optimization with requiring all scripts up front is about 20%
faster than the default configuration.</p>
</div>
<div class="section" id="results-with-apc">
<h2>Results with APC</h2>
<table border="1" class="docutils">
<colgroup>
<col width="42%"/>
<col width="21%"/>
<col width="16%"/>
<col width="21%"/>
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td>Include Strategy</td>
<td>Response time</td>
<td>Trans/sec</td>
<td>Performance %</td>
</tr>
<tr class="row-even"><td>Autoload, default include path</td>
<td>0.11</td>
<td>45.76</td>
<td>100%</td>
</tr>
<tr class="row-odd"><td>Autoload, swapped include path</td>
<td>0.09</td>
<td>53.05</td>
<td>81,81%</td>
</tr>
<tr class="row-even"><td>Autoload, ZF w/o require_once</td>
<td>0.08</td>
<td>60.90</td>
<td>72,72%</td>
</tr>
<tr class="row-odd"><td>No-Autoload, require up front</td>
<td>0.07</td>
<td>73.99</td>
<td>63,63%</td>
</tr>
</tbody>
</table>
<p>Turning APC on gives a boost of about 50% to your application no matter
what include strategy you are following (so there is excuse not using
APC). But switching between different include strategies still makes a
huge difference in performance. Percentage-wise this is a larger
difference than without APC. Requiring all dependent scripts up front
takes only about 63% of the default configuration time, which can make a
major difference on any production server.</p>
<p>In an application knowing which includes of the Zend Framework will be
needed on each request is difficult, since different helpers and classes
might be needed based on which url is requested. It maybe a good
practice to just include all the classes that might be needed. If this
is a job to hard to do you can still get lots of performance gain out of
your application by fixing the include path, using Zend Loaders Autoload
and stripping all require_once calls from all of the Zend Framework
files.</p>
</div>
</div>]]></description>
            <pubDate>Thu, 28 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/16/zendx-jquery-is-ready-for-recommendation.html</link>
            <guid>http://www.whitewashing.de/2008/08/16/zendx-jquery-is-ready-for-recommendation.html</guid>
            <title><![CDATA[ZendX_JQuery is Ready for Recommendation]]></title>
            <description><![CDATA[<div class="section" id="zendx-jquery-is-ready-for-recommendation">
<h1>ZendX_JQuery is Ready for Recommendation</h1>
<p>Yesterday night I finished the <a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery_View_Helper_JQuery+-+Benjamin+Eberlei">proposal for
ZendX_JQuery</a>,
a View Helper and an Ajax Helper hopefully to be included in the <a class="reference external" href="http://framework.zend.com">Zend
Framework</a> Extras Library in the next
release after 1.6. I moved the proposal to the “Ready for
Recommendation” section now, so it can be reviewed a last time by the
community and by the Zend people.</p>
<p>For those people already using an earlier version, i have squashed about
4-5 bugs I found writing the Unit-Tests for this component. The test
coverage for both helpers is 100% although the jQLink Helper might need
some additional Use-Case scenarios to ensure proper working. You can
<a class="reference external" href="http://www.beberlei.de/dev/svn/ZendX_JQuery">find the current
version</a> at my SVN
repository.</p>
</div>]]></description>
            <pubDate>Sat, 16 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/10/import-and-pythonpath-problems-with-pydev-and-linux.html</link>
            <guid>http://www.whitewashing.de/2008/08/10/import-and-pythonpath-problems-with-pydev-and-linux.html</guid>
            <title><![CDATA[Import and PYTHONPATH Problems with PyDev and Linux]]></title>
            <description><![CDATA[<div class="section" id="import-and-pythonpath-problems-with-pydev-and-linux">
<h1>Import and PYTHONPATH Problems with PyDev and Linux</h1>
<p>Today is began to configure my <a class="reference external" href="http://pydev.sf.net">PyDev</a> Eclipse
environment since I want to learn Python and need it for a programming
aspect of my forthcoming diploma thesis. I ran into several difficulties
getting the plugins run dialog to work. It seems that configuring the
python interpreter under linux and adding all the correct include paths
is not enough, even when following the <a class="reference external" href="http://pydev.sourceforge.net/faq.html#how_do_i_configure_my_pythonpath">PyDev
FAQ</a>.</p>
<p>Nearly giving up I came up with sort of a hack to get it running.
Eclipse can execute arbitrary “External Tools” (Find it at: “<strong>Run -&gt;
External Tools -&gt; Open External Tools Dioalog</strong>”). I used this facility
to integrate an external tool “Python” with path “<strong>/usr/bin/python</strong>”.
Now to automatically execute the currently active python script, you can
specify the line: “<strong>${resource_loc}</strong>” in the arguments field of the
dialog and you’re good to go.</p>
<p>You now circumvented the PyDev internal execution scheme and work with
the pure command line interpreter. This way all the problems of PyDev
with the PythonPath, Symlinks and whatever are gone.</p>
<p><strong>Update:</strong> Another note maybe, you can also add the action “running the
last used external tool again” as keyboard shortcut in the Eclipse
preferences. This simplifies the execution even more.</p>
</div>]]></description>
            <pubDate>Sun, 10 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/04/complete-django-template-engine-implementation-for-php5-downloadable-now.html</link>
            <guid>http://www.whitewashing.de/2008/08/04/complete-django-template-engine-implementation-for-php5-downloadable-now.html</guid>
            <title><![CDATA[Complete Django Template Engine Implementation for PHP5 - Downloadable Now]]></title>
            <description><![CDATA[<div class="section" id="complete-django-template-engine-implementation-for-php5-downloadable-now">
<h1>Complete Django Template Engine Implementation for PHP5 - Downloadable Now</h1>
<p>I prepared a downloadable version of my <a class="reference external" href="http://www.djangoproject.com">Django Template
Language</a> Engine Clone for PHP5 and the
Zend Framework (although it can easily be used Standalone). It also
implements two helpers that aid in rapid ajax/Dojox deployment. You can
easily specify template blocks that should be rendered by Javascript via
DojoX DTL, which are then marked, compiled and shown by the client using
JSON data from the server. I included a demo to show this feature.</p>
<p>You can grab the
<a class="reference external" href="http://www.beberlei.de/sources/calypso-dtl-0.1.tar.gz">Tarball</a> and
there is also a
<a class="reference external" href="http://www.beberlei.de/sources/README_Dtl.txt">README</a> with some
information. I would appreciate if anybody would test the lib and gave
some feedback.</p>
<p>I will soon start to push this component in the ZF proposal process. I
still have to finish the class structure before I can move to the Ready
for Review stage. The library will max end up in Zend Extras. Therefore
I will have to say again: This View Renderer shall be no replacement for
the current Zend View. It is only an alternative which allows for some
neat functionality and stricter View / Controller logic separation.</p>
<p><strong>UPDATE:</strong> I finished a little page for what I call the Calypso DTL.
See it here: <a class="reference external" href="http://www.beberlei.de/calypso/">Calypso Site</a>. I have
put up a little tutorial how to get the Template Engine running with
Zend Framework and as a standalone component.</p>
</div>]]></description>
            <pubDate>Mon, 04 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/08/31/greaat-python-can-control-your-wiimote.html</link>
            <guid>http://www.whitewashing.de/2008/08/31/greaat-python-can-control-your-wiimote.html</guid>
            <title><![CDATA[Greaat, Python can control your Wiimote]]></title>
            <description><![CDATA[<div class="section" id="greaat-python-can-control-your-wiimote">
<h1>Greaat, Python can control your Wiimote</h1>
<p>In the last days I had lots of time to play with my Wiimote and its
bluetooth capabilities. Sadly there is actively supported driver in non-C
(and I am not the biggest C programmer). I found this little prototype
driver written in Python by Will Woods which is using pyBluez to
communicate with my wiimote and have extended it quite a bit.
<a class="reference external" href="http://www.wiili.org">WiiLinux</a> is a huge resource that offers
information on reverse engineering of the Wiimote protocol.</p>
<p>The driver is still far from finished or usable outside some demo
applications, but that might still be included in the future. You can
<a class="reference external" href="http://www.beberlei.de/sources/wiipylib-0.1.tar.gz">download this little
goodie</a> and have a
look at it.</p>
</div>]]></description>
            <pubDate>Sun, 31 Aug 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/23/constructions.html</link>
            <guid>http://www.whitewashing.de/2008/01/23/constructions.html</guid>
            <title><![CDATA[Constructions...]]></title>
            <description><![CDATA[<div class="section" id="constructions">
<h1>Constructions...</h1>
<p>Some people complained: Yes comments do not work YET, and also the links
behind categories and Tags show nothing. Everything else follows
shortly. I am programming this whole blog using the <a class="reference external" href="http://framework.zend.com">Zend
Framework</a> to have a bit of learning
experience. It will take some more time than if I would do it in “the
old ways”.</p>
</div>]]></description>
            <pubDate>Wed, 23 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/14/helpers-in-zend-view-class-prefix.html</link>
            <guid>http://www.whitewashing.de/2008/01/14/helpers-in-zend-view-class-prefix.html</guid>
            <title><![CDATA[Helpers in Zend_View: Class Prefix]]></title>
            <description><![CDATA[<div class="section" id="helpers-in-zend-view-class-prefix">
<h1>Helpers in Zend_View: Class Prefix</h1>
<p>I have to say, the Zend Framework documentation is a bit imprecise
sometimes. Regarding custom Helpers in Zend_View it states:</p>
<blockquote>
<div>The class name must, at the very minimum, end with the helper name
itself, using CamelCaps. E.g., if you were writing a helper called
“specialPurpose”, the class name would minimally need to be
“SpecialPurpose”. You may, and should, give the class name a prefix,
and it is recommended that you use ‘View_Helper’ as part of that
prefix: “My_View_Helper_SpecialPurpose”. (You will need to pass
in the prefix, with or without the trailing underscore, to
addHelperPath() or setHelperPath()).</div></blockquote>
<p>What does that mean regarding how your Helper has to be called? The
default prefix for a Helper function that should be called foobar() is
actually:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class Zend_View_Helper_Foobar()</span>
<span class="x">{</span>
<span class="x">    function foobar() { }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>It took me some time to realize that. Why doesn’t Zend just give an
example like that? To change the prefix in a context of the
Zend_Controller_Action you have to do something like this:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class SomeController extends Zend_Controller_Action</span>
<span class="x">{</span>
<span class="x">    function init() {</span>
<span class="x">        $this-&gt;initView();</span>
<span class="x">        $this-&gt;view-&gt;addHelperPath(&quot;pathtohelpers&quot;, &quot;ClassPrefix&quot;);</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
</div>]]></description>
            <pubDate>Mon, 14 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/22/a-knight-s-tour-solver-in-pascal.html</link>
            <guid>http://www.whitewashing.de/2008/01/22/a-knight-s-tour-solver-in-pascal.html</guid>
            <title><![CDATA[A knight's tour solver in pascal]]></title>
            <description><![CDATA[<div class="section" id="a-knight-s-tour-solver-in-pascal">
<h1>A knight’s tour solver in pascal</h1>
<p>My professor has a task on the current problem set of my pascal
programming course to program, demanding a recursive program finding a
solution to the <a class="reference external" href="http://en.wikipedia.org/wiki/Knight's_tour">knights tour problem</a> on a chess board
of size n&gt;=3 given a starting position. I used a backtracking algorithm
(at least that is what wikipedia tells me it is), by trying all possible
combinations and setting steps back, when they do not lead to a
solution.</p>
<p>Beginning with n = 7 my algorithms gets very slow, caused by the
backtracking algorithm which is not very efficient. I found some
interesting articles regarding this problem using graph theory to solve
it. Some pretty big minds have thought about the problem, I guess its
not for me to find such an solution for a little task of the weekly
problem set.</p>
<ul class="simple">
<li><a class="reference external" href="http://mathworld.wolfram.com/KnightsTour.html">Wolfram MathWorld: Knights Tour</a></li>
<li><a class="reference external" href="http://www.zaik.uni-koeln.de/AFS/teachings/ss07/InfoSeminar/handout/leonid_torgovitski_nknighttours.pdf">Presentation Knights Tour (German Language)</a></li>
</ul>
</div>]]></description>
            <pubDate>Tue, 22 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/22/knights-tour-using-warndorff-s-rule.html</link>
            <guid>http://www.whitewashing.de/2008/01/22/knights-tour-using-warndorff-s-rule.html</guid>
            <title><![CDATA[Knights Tour using Warndorff's rule]]></title>
            <description><![CDATA[<div class="section" id="knights-tour-using-warndorff-s-rule">
<h1>Knights Tour using Warndorff’s rule</h1>
<p>When using <a class="reference external" href="http://web.telia.com/~u85905224/knight/eWarnsd.htm">Warndorff’s
rule</a> for solving
the Knights Tour problem, the solution is found within a second. It took
some time for me to realize it in PASCAL though using a <strong>RECORD</strong> type
to match the jumps to the number of free fields and then sort them. You
can view my source code
<a class="reference external" href="http://www.beberlei.de/sources/knightstour.txt">here</a>.</p>
</div>]]></description>
            <pubDate>Tue, 22 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/22/a-knight-s-tour-solver-in-pascal-supplement.html</link>
            <guid>http://www.whitewashing.de/2008/01/22/a-knight-s-tour-solver-in-pascal-supplement.html</guid>
            <title><![CDATA[A knight's tour solver in pascal - supplement]]></title>
            <description><![CDATA[<div class="section" id="a-knight-s-tour-solver-in-pascal-supplement">
<h1>A knight’s tour solver in pascal - supplement</h1>
<p>Following my <a class="reference external" href="http://www.whitewashing.de/blog/articles/6">earlier post on the Knights
tour</a>: It seems it is
crucial for a backtracking algorithm what the knights starting position
is, and even more important in what order the jumps are tried. Because
there are 8 possible moves for a knight, you have to decide in which
order they should be performed. If there is not a deviation when
backtracking the algorithm gets stuck in almost the same positions very
very often.</p>
<p>I rewrote the order of jumps for my 7x7 board and found a solution in
seconds. Using the same order for an 8x8 board gets me stuck in endless
tries again. I see its important to implement the <a class="reference external" href="http://en.wikipedia.org/wiki/Warnsdorff's_algorithm">Warnsdorff’s
algorithm</a>,
perhaps I will do so.</p>
</div>]]></description>
            <pubDate>Tue, 22 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/28/linux-style-mysql-shell-prompt.html</link>
            <guid>http://www.whitewashing.de/2008/01/28/linux-style-mysql-shell-prompt.html</guid>
            <title><![CDATA[Linux style MySQL Shell prompt]]></title>
            <description><![CDATA[<div class="section" id="linux-style-mysql-shell-prompt">
<h1>Linux style MySQL Shell prompt</h1>
<dl class="docutils">
<dt>Just add the following to the [mysql] section in your .my.cnf file:</dt>
<dd><div class="first last highlight-python"><pre>prompt=\u@\h [\d]&gt;\</pre>
</div>
</dd>
</dl>
</div>]]></description>
            <pubDate>Mon, 28 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/27/writing-a-game-for-kde4.html</link>
            <guid>http://www.whitewashing.de/2008/01/27/writing-a-game-for-kde4.html</guid>
            <title><![CDATA[Writing a Game for KDE4]]></title>
            <description><![CDATA[<div class="section" id="writing-a-game-for-kde4">
<h1>Writing a Game for KDE4</h1>
<p>I am writing PHP / Web Applications for about 8 years now, but I am not
so much the pro in writing desktop applications. I know little or no
C/C++/Java, but want to change that soon. Since I use KDE for both my
desktop and laptop it seems reasonable to write a KDE 4 application.</p>
<p>What about ideas? I wanted to write a game for so long and in the last
years my girlfriend and I tried lots of 2 person player games. One of
them I wanted to re-create as a computer game.</p>
<p>The possibilities are:</p>
<ul class="simple">
<li><a class="reference external" href="http://en.wikipedia.org/wiki/Game_of_the_Amazons">The Game of the
Amazons</a></li>
<li><a class="reference external" href="http://www.wikimanqala.org/wiki/Moruba">Moruba</a> - Oware or a
variant.</li>
</ul>
<p>All 3 games are time intensive and very strategic. Moruba can be played
for lots of hours (My gf and I played one game for about 5-6 hours). Its
probably more easy to write algorithms for the computer player of Oware
or Moruba than for Amazons, but that should not affect my decision. I
will decide in the next weeks, but I should probably concentrate on my
semesters final exams in the first place.</p>
<p><strong>Update:</strong> Moruba seems to have different rules than the game we are
playing. I will elaborate on that soon.</p>
</div>]]></description>
            <pubDate>Sun, 27 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/20/zend-view-hack-for-implementation-of-rss-feed.html</link>
            <guid>http://www.whitewashing.de/2008/01/20/zend-view-hack-for-implementation-of-rss-feed.html</guid>
            <title><![CDATA[Zend_View Hack for implementation of RSS Feed]]></title>
            <description><![CDATA[<div class="section" id="zend-view-hack-for-implementation-of-rss-feed">
<h1>Zend_View Hack for implementation of RSS Feed</h1>
<p>Using Zend_View for your site and want to implement an RSS Feed? You
might run into the problem that the XML header definition is interpreted
as PHP code:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?</span><span class="nx">xml</span> <span class="nx">version</span><span class="o">=</span><span class="s2">&quot;1.0&quot;</span> <span class="nx">encoding</span><span class="o">=</span><span class="s2">&quot;ISO-8859-1&quot;</span><span class="cp">?&gt;</span><span class="x"/>
</pre></div>
</div>
<p>Before you start cursing the world try this (rather obvious) workaround:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="s1">'&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;'</span><span class="p">;</span> <span class="cp">?&gt;</span><span class="x"/>
</pre></div>
</div>
</div>]]></description>
            <pubDate>Sun, 20 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/20/using-a-self-defined-zend-loader.html</link>
            <guid>http://www.whitewashing.de/2008/01/20/using-a-self-defined-zend-loader.html</guid>
            <title><![CDATA[Using a self defined Zend_Loader]]></title>
            <description><![CDATA[<div class="section" id="using-a-self-defined-zend-loader">
<h1>Using a self defined Zend_Loader</h1>
<p>When you start writing with a Framework like Zend like I did in the last
weeks, you probably are still haunted by all the bad habits of pseudo
object orientated PHP design, using lots of require and include’s.
Zend_Loader doesn’t seem to help at first, its just another command
(Zend_Loader::loadClass or ::loadFile). It sucks to register lots of
autoload paths too.</p>
<p>I wrote my own Zend_Loader child class. It grabs all include paths from
a config File using the Zend_Config class, and completely frees you of
thinking about includes.</p>
<blockquote>
<div><div class="highlight-python"><pre>class WWLoader extends Zend_Loader
{
    private static $dirs = NULL;

    public static function loadClass($class)
    {
        if(self::$dirs===NULL) {
            //
            // Include directories of this application are saved in a configuration file. If it has not been
            // loaded before do so now and safe everything to the private static variable $dirs which will
            // then be used in further loadings
            //
            $dirs = array();
            $conf_app_path = new Zend_Config_Ini(sprintf('%s%s', constant('ZEND_CONFIG_PATH'), 'application.ini'), 'appincludepath');
            self::extractPaths($conf_app_path-&gt;toArray(), $dirs);
            self::$dirs = $dirs;
        }

        parent::loadClass($class, self::$dirs, true);
    }

    public static function autoload($class)
    {
        try {
            self::loadClass($class);
            return $class;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Given an array with subkeys of include paths this function unifies this array to
     * a single one and returns the result in the second argument $dirs which is given
     * by reference.
     *
     * @param Array $array
     * @param Array $dirs
     */
    public static function extractPaths($array, &amp;$dirs)
    {
        foreach($array AS $k =&gt; $v) {
            if(is_array($v)) {
                self::extractPaths($v, $dirs);
            } else {
                $dirs[] = $v;
            }
        }
    }
}</pre>
</div>
</div></blockquote>
<p>ZEND_CONFIG_PATH is the only constant I use in my application. I
initialize the following at the beginning of my bootstrap file:</p>
<blockquote>
<div><div class="highlight-python"><pre>define('ZEND_CONFIG_PATH', dirname(__FILE__).&quot;/../application/config/&quot;);

require_once 'Zend/Loader.php';
require_once dirname(__FILE__).'/../application/include/WWLoader.php';
Zend_Loader::registerAutoload();
Zend_Loader::registerAutoload('WWLoader');</pre>
</div>
</div></blockquote>
<p>After that, its just Objects.</p>
</div>]]></description>
            <pubDate>Sun, 20 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/17/zf-managing-404-errors-with-version-1-0-3.html</link>
            <guid>http://www.whitewashing.de/2008/01/17/zf-managing-404-errors-with-version-1-0-3.html</guid>
            <title><![CDATA[ZF: Managing 404 Errors with Version 1.0.3]]></title>
            <description><![CDATA[<div class="section" id="zf-managing-404-errors-with-version-1-0-3">
<h1>ZF: Managing 404 Errors with Version 1.0.3</h1>
<p>Ok, the description of the Link referring to the <a class="reference external" href="http://www.bigroom.co.uk/blog/managing-404-errors-in-the-zend-framework">version 0.9 solution
for Managing 404
errors</a>
due to missing modules or actions is wrong. It is not enough to replace
Zend::loadClass with Zend_Loader::loadClass. Other functions have been
renamed, my current snippet is:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">/**</span>
<span class="x"> * Original Snippet from: http://www.bigroom.co.uk/blog/managing-404-errors-in-the-zend-framework</span>
<span class="x"> */</span>
<span class="x">    class NoroutePlugin extends Zend_Controller_Plugin_Abstract</span>
<span class="x">    {</span>
<span class="x">        public function preDispatch(Zend_Controller_Request_Abstract $request )</span>
<span class="x">        {</span>
<span class="x">            $dispatcher = Zend_Controller_Front::getInstance()-&gt;getDispatcher();</span>

<span class="x">            $controllerName = $request-&gt;getControllerName();</span>
<span class="x">            if (empty($controllerName)) {</span>
<span class="x">                $controllerName = $dispatcher-&gt;getDefaultControllerClass($request);</span>
<span class="x">            }</span>
<span class="x">            $className = $dispatcher-&gt;formatControllerName($controllerName);</span>
<span class="x">            if ($className)</span>
<span class="x">            {</span>
<span class="x">                try</span>
<span class="x">                {</span>
<span class="x">                    // if this fails, an exception will be thrown and</span>
<span class="x">                    // caught below, indicating that the class can't</span>
<span class="x">                    // be loaded.</span>
<span class="x">                    Zend_Loader::loadClass($className, $dispatcher-&gt;getControllerDirectory());</span>
<span class="x">                    $actionName = $request-&gt;getActionName();</span>
<span class="x">                    if (empty($actionName)) {</span>
<span class="x">                        $actionName = $dispatcher-&gt;getDefaultAction();</span>
<span class="x">                    }</span>
<span class="x">                    $methodName = $dispatcher-&gt;formatActionName($actionName);</span>

<span class="x">                    $class = new ReflectionClass( $className );</span>
<span class="x">                    if( $class-&gt;hasMethod( $methodName ) )</span>
<span class="x">                    {</span>
<span class="x">                        // all is well - exit now</span>
<span class="x">                        return;</span>
<span class="x">                    }</span>
<span class="x">                }</span>
<span class="x">                catch (Zend_Exception $e)</span>
<span class="x">                {</span>
<span class="x">                    // Couldn't load the class. No need to act yet,</span>
<span class="x">                    // just catch the exception and fall out of the</span>
<span class="x">                    // if</span>
<span class="x">                }</span>
<span class="x">            }</span>

<span class="x">            // we only arrive here if can't find controller or action</span>
<span class="x">            $request-&gt;setControllerName( 'blog' );</span>
<span class="x">            $request-&gt;setActionName( 'noroute' );</span>
<span class="x">            $request-&gt;setDispatched( false );</span>
<span class="x">        }</span>
<span class="x">    }</span>
</pre></div>
</div>
<p>I hope someone needs this as much as me.</p>
</div>]]></description>
            <pubDate>Thu, 17 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/24/complaining-about-zend-filter-input.html</link>
            <guid>http://www.whitewashing.de/2008/01/24/complaining-about-zend-filter-input.html</guid>
            <title><![CDATA[Complaining about Zend_Filter_Input]]></title>
            <description><![CDATA[<div class="section" id="complaining-about-zend-filter-input">
<h1>Complaining about Zend_Filter_Input</h1>
<p>Zend_Filter_Input is really nice to be sure form data is filtered
correctly, but i have some serious complaints: Why the hell are the
error messages so user-unfriendly? I really would like to use the output
of Zend_Filter_Input::getMessages(), but I could never trust to show
them to a user of my website: They are obviously written for developers.
Some examples:</p>
<blockquote>
<div>‘’ does not appear to be an integer ‘’ is an empty string</div></blockquote>
<p>I use a ton of validators to filter the comments form and all possible
error messages that can be thrown are not “user-save”. Because all these
messages are handled in each Validator class its almost impossible to
change them without going nuts:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">$validators = array(</span>
<span class="x">    'article_id' =&gt; array(</span>
<span class="x">        'Int',</span>
<span class="x">        new Zend_Validate_Int(),</span>
<span class="x">        array('GreaterThan', 0)</span>
<span class="x">        ),</span>
<span class="x">    'username' =&gt; 'Alnum',</span>
<span class="x">    'userEmail' =&gt; new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS | Zend_Validate_Hostname::ALLOW_LOCAL, true),</span>
<span class="x">    'cp'   =&gt; array(</span>
<span class="x">        'Digits',                // string</span>
<span class="x">        new Zend_Validate_Int(), // object instance</span>
<span class="x">        array('Between', 1138, 1138)  // string with constructor arguments</span>
<span class="x">    ),</span>
<span class="x">    'comment' =&gt; 'NotEmpty',</span>
<span class="x">);</span>
</pre></div>
</div>
<p>This simple $validators requirement creates templates for error
messages in each validator object, that are: Zend_Validate_Int,
Zend_Validate_Alnum, Zend_Validate_EmailAddress,
Zend_Validate_Hostname, and the not empty message. To allow for user
friendly messages one had to make child objects of each of the
Validators and edit the error messages accordingly. I avoid this by
printing my own errors from outside the Zend_Filter_Input, rather than
using the object for what it is probably supposed to do.</p>
</div>]]></description>
            <pubDate>Thu, 24 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/01/24/how-my-zend-db-table-models-look-like.html</link>
            <guid>http://www.whitewashing.de/2008/01/24/how-my-zend-db-table-models-look-like.html</guid>
            <title><![CDATA[How my Zend_Db_Table models look like]]></title>
            <description><![CDATA[<div class="section" id="how-my-zend-db-table-models-look-like">
<h1>How my Zend_Db_Table models look like</h1>
<p>I am not too happy with the ZF Frameworks Table access solution. Not
that I have anything against the <a class="reference external" href="http://martinfowler.com/eaaCatalog/tableDataGateway.html">Table Gateway
pattern</a>,
but in most web applications you almost always have to join data some
way or another. Even this rather simple application, a blog, needs joins
for displaying articles so that category, comment count and tags can be
displayed. Therefore I use an instance of Zend_Db_Table_Abstract only
for the simplest purposes and pimp it by using lots of public methods
and
<a class="reference external" href="http://framework.zend.com/manual/en/zend.db.select.html">Zend_Db_Select</a>.
An example:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class SomeModel extends Zend_Db_Table_Abstract</span>
<span class="x">{</span>
<span class="x">  $_name = &quot;someTable&quot;;</span>
<span class="x">  $_primary = &quot;id&quot;;</span>

<span class="x">  public function getSomethingByJoin($param1, $param2)</span>
<span class="x">  {</span>
<span class="x">     $db = $this-&gt;getAdapter();</span>
<span class="x">     $select = $db-&gt;select();</span>
<span class="x">     ...[build select]</span>
<span class="x">     $result = $db-&gt;query($select);</span>

<span class="x">     return $result;</span>
<span class="x">  }</span>
<span class="x">}</span>
</pre></div>
</div>
<p>That way you still follow the MVC pattern and don’t have to take one
compromise after another for getting the Table Gateway to reproduce a
result that looks like a join.</p>
</div>]]></description>
            <pubDate>Thu, 24 Jan 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/10/30/php-conference-recap-netbeans-ezcomponents-mapreduce.html</link>
            <guid>http://www.whitewashing.de/2008/10/30/php-conference-recap-netbeans-ezcomponents-mapreduce.html</guid>
            <title><![CDATA[PHP Conference Recap: NetBeans, ezComponents, MapReduce..]]></title>
            <description><![CDATA[<div class="section" id="php-conference-recap-netbeans-ezcomponents-mapreduce">
<h1>PHP Conference Recap: NetBeans, ezComponents, MapReduce..</h1>
<p>This years october edition of <a class="reference external" href="http://www.phpconference.de">IPC</a> in
Mainz, Germany was the first php conference I have been to. It ended
some hours ago and i am quite happy to have been there. I had several
great discussions which pointed me to new stuff (to follow) and also met
great people.</p>
<p>First thing that completely fascinated me is <a class="reference external" href="http://download.netbeans.org/netbeans/6.5/rc/">NetBeans 6.5 with PHP
support</a>. It feels much
more easy to use than Eclipse PDT. Its faster (from the little tests i
could make) and does not strike when you add several large libraries
into the include path. It offers much more help on refactoring and
organizing than Eclipse PDT does, for example it offers to generate
getter/setter, constructor, inheritance methods. Much thanks to Petr who
explained to me in detail how NetBeans works.</p>
<p>Ez had lots of people at the conference (to Kore and Tobias i spoke in
more detail) and I had some talks with them about
<a class="reference external" href="http://www.ezcomponents.org">ezComponents</a>. This was especially
interesting after the great session on object persistence in ez, as well
when I heard that ezcMvc, a model-view-controller component, wil be
included in the next release of ezc in December 2008. ezComponents has a
Database layer, that does not seem to enforce too much overhead on you
but still offers great extensibility through a persistence layer and a
library that offers to build Database Diffs. The latter feature is
really great and I will definitely have a look at this.</p>
<p>Sebastian Bergmann had a great talk on MapReduce which is an old LISP
programming paradigm to work with huge datasets. This style was recently
<a class="reference external" href="http://labs.google.com/papers/mapreduce.html">revived by Google</a>
because tasks can easily be split and distributed for computing on
different nodes with hundreds of threads. Implementing a working example
in PHP is really easy, just finding a good way to process your large
data seems to be a topic that needs lots of thinking.</p>
<p>Additional great things:</p>
<ul class="simple">
<li>Meet Thomas, the guy that wrote Weaverslave (I use it for years to
build simple php applications).</li>
<li>He is working on a cool open source project <a class="reference external" href="http://sourceforge.net/projects/ccg/">Carica
Cachegrind</a> with Bastian
Feder that will process xdebug cachegrind files via a webinterface
(They told me webgrind is actually calculating the numbers wrong).</li>
<li>Jan Lehnhart and Kore Nordmann had some great things to say about
<a class="reference external" href="http://incubator.apache.org/couchdb/">CouchDB</a>.</li>
<li>Brian Acker talked about <a class="reference external" href="https://launchpad.net/drizzle">Drizzle</a>,
which is a forked MySQL that throws out lots of legacy stuff from
MySQL out, to build a micro-kernel database server that suites the
web.</li>
<li>Ulf Wendel talked about Mysqli + Mysqlnd.
<a class="reference external" href="http://dev.mysql.com/downloads/connector/php-mysqlnd/">Mysqlnd</a>
will be a new internal driver for PHP to access MySQL through Mysqli
and optimizes processing and memory consumption. Additionally Mysqli
will be extended to offer asynchronous queries that can be fired at
the database and polled latter. To be included in PHP 5.3</li>
</ul>
<p>Not so good things: There were absolutely to few power lines. People
using their notebooks were packed on hotspots where power was available.
Please more power plug possibilities next time!</p>
</div>]]></description>
            <pubDate>Thu, 30 Oct 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/10/01/my-recent-zf-ongoings-jquery-action-controller-couchdb.html</link>
            <guid>http://www.whitewashing.de/2008/10/01/my-recent-zf-ongoings-jquery-action-controller-couchdb.html</guid>
            <title><![CDATA[My recent ZF ongoings: JQuery, Action Controller, CouchDb]]></title>
            <description><![CDATA[<div class="section" id="my-recent-zf-ongoings-jquery-action-controller-couchdb">
<h1>My recent ZF ongoings: JQuery, Action Controller, CouchDb</h1>
<p>In the last weeks lots of stuff came up for me regarding the Zend
Framework. My <a class="reference external" href="http://jquery.com">jQuery</a> component is finished, i
have even committed the documentation into the SVN already. Do read it
you have to be either an XML fetishist or compile it using a docbook
compiler. Lots of questions about ZF and jQuery come up regularly on the
mailing lists so I really look forward for the first ZF 1.7 release
candidate which will include the helpers for a broader audience. This
component comes at a good point, since <a class="reference external" href="http://jquery.com/blog/2008/09/28/jquery-microsoft-nokia/">a few days ago the jQuery team
announced a deal with Microsoft and
Nokia</a>.
Microsoft will include jQuery as the framework to go into its Webbased
ASP.Net applications and Nokia will include the library in their mobile
phones.</p>
<p>Additionally i reported an <a class="reference external" href="http://framework.zend.com/issues/browse/ZF-4385">important issue
(ZF-4385)</a> that
offers a patch to create an interface of the Action Controller and
therefore allows everyone to implement their own action controller
classes. May it be lightweight implementations or like my current
use-case webservice only controllers that route all their actions
through soap, xml-rpc or a rest server. I would really appreciate if
more people would vote +1 on this issue to get it included in 1.7</p>
<p>In the last weeks i also played around with
<a class="reference external" href="http://incubator.apache.org/couchdb/docs/overview.html">CouchDb</a>, a
document based database. Its the perfect storage medium for blogs, wikis
or other knowledge-based applications and comes with a lightweight and
easy REST Api for ClientSide access. Within the
<a class="reference external" href="http://www.zym-project.com">Zym</a> project i managed to implement a
prototype that is based on Jurrien’s prototype for a CouchDb client.
<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Couch+-+Matthew+Weier+O'Phinney">Matthew of Zend Fame published a proposal for a Zend
Couch</a>
component yesterday and we teamed up to implement two prototypes
(<a class="reference external" href="http://github.com/weierophinney/phly/tree/beberlei">mine</a> is based
on <a class="reference external" href="http://github.com/weierophinney/phly/tree/master">Matthews</a> and
integrates lots of stuff of the Zym component).</p>
</div>]]></description>
            <pubDate>Wed, 01 Oct 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/04/27/ox-cross-correlation-coefficients-with-lags.html</link>
            <guid>http://www.whitewashing.de/2008/04/27/ox-cross-correlation-coefficients-with-lags.html</guid>
            <title><![CDATA[Ox: Cross-correlation coefficients with lags]]></title>
            <description><![CDATA[<div class="section" id="ox-cross-correlation-coefficients-with-lags">
<h1>Ox: Cross-correlation coefficients with lags</h1>
<p>Working on the homework for my <a class="reference external" href="http://mueller.gernot.googlepages.com/monetaryeconomics">Monetary Economics
class</a> I
realized that <a class="reference external" href="http://www.doornik.com">Ox</a> has different mechanisms to
calculate correlation coefficients like Mathlab has.</p>
<p>Our assignment was to replicate the Dynamic Correlations graph in
<a class="reference external" href="http://www.amazon.de/gp/redirect.html?ie=UTF8&amp;location=http://www.amazon.de/Monetary-Theory-Policy-Carl-Walsh/dp/0262232316?ie=UTF8&amp;s=books-intl-de&amp;qid=1209289935&amp;sr=8-1&amp;site-redirect=de&amp;tag=economystuden-21&amp;linkCode=ur2&amp;camp=1638&amp;creative=6742">Walshs’ Monetary Theory and
Policy</a>
for European Data, which shows the cross-correlation of different
monetary aggregates (M0,M1,M2) with GDP over lagging periods of -8 to +8
quarters.</p>
<p>What was missing for me to do that assignment in Ox was a function to
calculate cross-correlation coefficients for two vectors for a specified
lag length:</p>
<blockquote>
<div><div class="highlight-python"><pre>#include &lt;oxfloat.h&gt;

/**
 * Computes the cross-correlation coefficient for two vector series allowing
 * to optionally specify the number of positive and negative lags the ccc
 * should be calculated for.
 *
 * @author Benjamin Eberlei (kontakt at beberlei dot de)
 * @param vVarY Tx1 vector of variable related to
 * @param vVarX Tx1 vector of variable which is tested in different lags
 * @param lags Integer indicating the number of negative and positive lags.
 * @returns (1+lags*2)*1 vector of correlations from -lags to lags
 **/
ccf(const vVarY, const vVarX, const lags)
{
    // Generate positive and negative lags of given length and fill with NaN, so
    // that rows with not available numbers can be dropped from calculating the CCF later on.
    decl mXLag = lag0(vVarX, range(lags, -lags), M_NAN);

    decl mCorr, sCov;

    // initialize result vector holding one crosscorrelation per lag
    decl vCorrLags = zeros(1+lags*2, 1);

    // sadly there are no matrix operations to ease this computation, loop over all lags
    for(decl i = 0; i &lt; 1+lags*2; i++) {
        mCorr = deleter(vVarY ~ mXLag[][i]); // stick y and current lagged x together and delete NaN rows

        // calculate covariance of both time series
        sCov = 1/(rows(mCorr)-1) * sumc( (mCorr[][0]-meanc(mCorr[][0]))' * (mCorr[][1]-meanc(mCorr[][1])) );

        // calculate correlation coefficient
        vCorrLags[i][0] = sCov / ( sqrt(varc(mCorr[][0])) * sqrt(varc(mCorr[][1])) );
    }

    return vCorrLags;
}</pre>
</div>
</div></blockquote>
<p>It may prove useful to someone.</p>
</div>]]></description>
            <pubDate>Sun, 27 Apr 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/09/05/jquery-component-approved-for-extras-library.html</link>
            <guid>http://www.whitewashing.de/2008/09/05/jquery-component-approved-for-extras-library.html</guid>
            <title><![CDATA[jQuery Component approved for extras library]]></title>
            <description><![CDATA[<div class="section" id="jquery-component-approved-for-extras-library">
<h1>jQuery Component approved for extras library</h1>
<p>Yesterday both my jQuery Helper proposals (<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery_View_Helper_JQuery+-+Benjamin+Eberlei">Core
Helper</a>,
<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery+UI+Widgets+Extension+-+Benjamin+Eberlei?focusedCommentId=7373203#comment-7373203">UI
Widgets</a>)
for the Zend Framework have been accepted for development. I have
already checked my working prototypes <a class="reference external" href="http://framework.zend.com/svn/framework/extras/incubator/">into the Zend Framework
SVN</a>. In my
opinion the usage is quite stable already. There is likely to be no
argument flip, function renaming or whatsoever. I have renamed the
jqLink helper to ajaxLink though, because other libraries are offering
the same functionality to make Ajax related calls and this way the
learning curve for people using different libraries in different
projects may be more easy.</p>
<p>What is still missing? I have to add captureStart()/captureEnd()
functions to the Container Widgets Accordion and Tabs, and will create
additional pane helpers for both of them. This will likely be finished
this weekend and then there is only the documentation missing. I am very
confident this component will be finished for the Zend Framework 1.7
release later this year.</p>
<p>Since this component also includes helpers for the jQuery UI Widgets 1.6
release (which is not released yet), a little waiting time before
release is still good. I hope this all works out and the jQuery UI 1.6
release is in the Google CDN, when ZF 1.7 comes out.</p>
</div>]]></description>
            <pubDate>Fri, 05 Sep 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/09/11/new-calypso-dtl-version-0-2.html</link>
            <guid>http://www.whitewashing.de/2008/09/11/new-calypso-dtl-version-0-2.html</guid>
            <title><![CDATA[New Calypso DTL Version 0.2]]></title>
            <description><![CDATA[<div class="section" id="new-calypso-dtl-version-0-2">
<h1>New Calypso DTL Version 0.2</h1>
<p>I have got some hints about bugs and optimized the performance of loops
a little bit, so that you can now <a class="reference external" href="http://www.beberlei.de/sources/calypso-dtl-0.2.tar.gz">download version
0.2</a> of the
<a class="reference external" href="http://www.beberlei.de/calypso">Calypso DTL template engine</a>. Have
fun.</p>
</div>]]></description>
            <pubDate>Thu, 11 Sep 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/09/20/dependency-injection-via-interface-in-php-an-example.html</link>
            <guid>http://www.whitewashing.de/2008/09/20/dependency-injection-via-interface-in-php-an-example.html</guid>
            <title><![CDATA[Dependency Injection via Interface in PHP: An example]]></title>
            <description><![CDATA[<div class="section" id="dependency-injection-via-interface-in-php-an-example">
<h1>Dependency Injection via Interface in PHP: An example</h1>
<p>Personal projects and work currently both force me to think about
application design and I <a class="reference external" href="http://www.martinfowler.com/articles/injection.html">came across dependency
injection</a> the
other day. Its quite a complex Design Pattern and hard to grasp, even
with the number of examples you can find in the internet. Basically
Dependency Injection means you register components that might be a
dependency for other components and when loading new classes via the
dependency injection framework, it knows of this relationships and
assembles the object in need and all its dependencies and returns them
fully initialized. This pattern leads to completely encapsulated objects
where any class in the object graph can be exchanged for a new
implementation without breaking all its dependencies. It also makes
testing complex components and object relationships very easy.</p>
<p>As far as I could find out, three different types of Dependency Injection
implementations exist: Via Constructor, via Setter and via Interfaces.
There exist implementations of Dependency Injection for Java (Spring)
that are configured via XML config files and seem very complex. They are
also hard to read in code I presume, since you always have to be aware
of the current application configuration. There are also some more
lightweight implementations (PicoContainer) that assemble their
relationships in the application and work with config methods that act
as configuration of the dependencies. <a class="reference external" href="http://www.martinfowler.com/articles/injection.html">Martin Folwer also discusses an
implementation via
interfaces</a>,
which seems most accessible for me.</p>
<p>All PHP clones of any dependency injection framework seem to go the
complex way via configuration though. With traits and multiple class
inheritance on the horizon, some kind of interface injection seems
mighty powerful though. So I implemented a really lightweight
implementation of Interface Dependency Injection for PHP. The Container
works with static method only, is therefore in the global scope, such
that configuration is reduced to a minimum. Generally you have to write
interfaces for object injection, for example:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">interface InjectDbAdapter</span>
<span class="x">{</span>
<span class="x">    public function injectDbAdapter(Zend_Db_Adapter_Abstract $db);</span>
<span class="x">}</span>
</pre></div>
</div>
<p>Other potential examples include “InjectLogger”, “InjectSoapClient”, or
“InjectAppConfig”. You then have to register a component for usage with
this interface:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">Whitewashing_Container::registerComponent('InjectDbAdapter', Zend_Db::factory($dbConfig));</span>
</pre></div>
</div>
<p>Now any class that implements the InjectDbAdapter interface can be
instantiated via:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">$obj = Whitewashing_Container::load('Class');</span>
</pre></div>
</div>
<p>and the loader takes care of calling the ‘Class’ implementation of
injectDbAdapter with the given Database Adapter. A negative consequence
of this approach is that you have to implement the inject methods for
all interfaces in your concrete class implementations. With Traits
(multiple class inheritance) being a new feature in PHP soon, injection
via parent classes seems to become a very powerful approach though,
which can handle the concrete implementations.</p>
<p>The Container takes care of all the dependency building, so when testing
your components you can register lots of mock objects. You can also
exchange dependencies for only a subset of objects very easily. I
implemented a method “Whitewashing_Container::registerClassComponent”,
which registers a dependency component that is used with higher priority
in construction of the given class. You can also specify a third
parameter $localInterfaceOverride for the highest priority:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">$obj = Whitewashing_Container::load('Class', null, array('InjectDbAdapter' =&gt; $newDbAdapter));</span>
</pre></div>
</div>
<p>Speedwise the usage of the Container reduces class instantiation by about
50%, from 0.5 sec for 10000 classes with setting dependencies to 1 sec
on my machine. But naturally only classes with dependencies and lots of
them should be using this mechanism and with good application design,
this shouldn’t be to many. You can download
<a class="reference external" href="http://www.beberlei.de/sources/WhitewashingContainer.phps">Container</a>
and <a class="reference external" href="http://www.beberlei.de/sources/di.phps">Example</a> sourcecode, to
take a look. Currently this Container is not really creating new
dependencies for each new class generation but rather inverts the usage
of a registry. It should be an easy task to extend the registering
method to decide between new class generation and using the globally
registered class instance.</p>
</div>]]></description>
            <pubDate>Sat, 20 Sep 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/30/dependency-injection-with-php-introducing-sphicy.html</link>
            <guid>http://www.whitewashing.de/2008/12/30/dependency-injection-with-php-introducing-sphicy.html</guid>
            <title><![CDATA[Dependency Injection with PHP: Introducing Sphicy]]></title>
            <description><![CDATA[<div class="section" id="dependency-injection-with-php-introducing-sphicy">
<h1>Dependency Injection with PHP: Introducing Sphicy</h1>
<p>I have written <a class="reference external" href="http://www.whitewashing.de/blog/articles/101">on dependency
injection</a> before
christmas and how <a class="reference external" href="http://code.google.com/p/guice">Guice</a>, googles DI
framework, offers a simple solution. I copied the functionality for a
PHP clone of Guice and named it
<a class="reference external" href="http://www.beberlei.de/sphicy">Sphicy</a>. You saw an early prototype of
it in the blogpost mentioned above.</p>
<p><a class="reference external" href="http://www.beberlei.de/sphicy">Sphicy</a> configures object dependencies
with modules: You explicitly state which implementation should be bound
to which interface. An injector then creates instances of these objects
via reflection: All constructor dependencies are resolved by looking at
the given type hints and initializes those according to the specified
bindings.</p>
<p>Two examples included in the <a class="reference external" href="http://www.beberlei.de/dev/svn/sphicy/">source code of
Sphicy</a> are <a class="reference external" href="http://framework.zend.com">Zend
Framework</a> and
<a class="reference external" href="http://www.ezcomponents.org">ezComponents</a> MVC bootstrapping modules.
Sadly both frameworks default front controllers are engineered in such a
way that useful dependency injection needs some workarounds.</p>
<p>As an example I will now discuss the Sphicy Module for Zend Framework
MVC applications. To circumvent the singleton and protected Constructor
of Zend_Controller_Front, we have to build a new front controller that
wraps around it and requires all the dependencies:</p>
<blockquote>
<div><div class="highlight-python"><pre>class Sphicy_Controller_Front
{
    protected $front;

    /**
     * Create Front Controller for Zend Framework using explicitly dependencies created by Sphicy.
     *
     * @param Zend_Controller_Request_Abstract      $request
     * @param Zend_Controller_Response_Abstract     $response
     * @param Zend_Controller_Router_Interface      $router
     * @param Zend_Controller_Dispatcher_Interface  $dispatcher
     */
    public function __construct(
        Zend_Controller_Request_Abstract $request,
        Zend_Controller_Response_Abstract $response,
        Zend_Controller_Router_Interface $router,
        Zend_Controller_Dispatcher_Interface $dispatcher=null
    )
    {
        $front = Zend_Controller_Front::getInstance();
        $front-&gt;setRequest($request);
        $front-&gt;setResponse($response);
        $front-&gt;setRouter($router);

        if($dispatcher === null) {
            $dispatcher = $front-&gt;getDispatcher();
        }
        $front-&gt;setDispatcher($dispatcher);
    }

    public function dispatch()
    {
        $this-&gt;front-&gt;dispatch();
    }
}</pre>
</div>
</div></blockquote>
<p>You can see that the <strong>Sphicy_Controller_Front</strong> class requires
dependencies in its constructor that are then forward injected into
<strong>Zend_Controller_Front</strong>. You can now create a module that binds all
the required dependencies to concrete implementations, for example a
module for a Zend MVC Http Application might look like:</p>
<blockquote>
<div><div class="highlight-python"><pre>class Sphicy_ZendMvc_ExampleModule implements spModule {
     public function configure(spBinder $binder) {
         // Sphicy_Controller_Front does not extend Zend_Controller_Front, because of Singletonitis
         // It offers the dispatch method to proxy against Zend_Controller_Front::dispatch.
         $binder-&gt;bind(&quot;Sphicy_Controller_Front&quot;)-&gt;to(&quot;Sphicy_Controller_Front&quot;);
         $binder-&gt;bind(&quot;Zend_Controller_Request_Abstract&quot;)-&gt;to(&quot;Zend_Controller_Request_Http&quot;);
         $binder-&gt;bind(&quot;Zend_Controller_Response_Abstract&quot;)-&gt;to(&quot;Zend_Controller_Response_Http&quot;);
         // loads all routes
         $binder-&gt;bind(&quot;Zend_Controller_Router_Interface&quot;)-&gt;to(&quot;MyApplication_Router&quot;);
     }
 }</pre>
</div>
</div></blockquote>
<p>The class <strong>MyApplication_Router</strong> might look up all the routing
information of the application via a hardcoded configuration mechanism.
You may say this is a hard dependency, but actually you can just switch
modules or implementations at this position to replace the router with
another implementation. You can also see that no implementation for the
dispatcher is bound. But this dependency is optional and will be created
automatically as can be seen in the <strong>Sphicy_Controller_Front</strong> class.</p>
<p>The front controllers is now created by calling:</p>
<blockquote>
<div><div class="highlight-python"><pre>$injector = new spDefaultInjector(new Sphicy_ZendMvc_ExampleModule());
$front = $injector-&gt;getInstance(&quot;Sphicy_Controller_Front&quot;);
$front-&gt;dispatch();</pre>
</div>
</div></blockquote>
<p>What happens in the <strong>$injector-&gt;getInstance()</strong> line? Sphicy looks at
<strong>Sphicy_Controller_Front</strong>‘s constructor and finds that four
dependencies are needed: Request, Response, Router and Dispatcher
implementations. It looks up the bindings and searches for them,
creating Zend_Controller_Request_Http,
Zend_Controller_Response_Http and MyApplication_Router objects. A
dispatcher implementation is not found, but Sphicy recognizes that null
is a valid paramater and injects it. The 3 concrete implementations and
one null are instantiated and used to construct a valid
<strong>Sphicy_Controller_Front</strong> instance.</p>
<p>You have now stated the dependencies of the Zend Controller Front
explicitly and can switch them instantaneously by switching the bindings
of interface to implementations in the configuration module.</p>
<p>Have a look at the <a class="reference external" href="http://www.beberlei.de/sphicy">Sphicy Website</a> and
<a class="reference external" href="http://www.beberlei.de/sphicy/documentation/faq.html">FAQ</a> to see
more examples and information about the possibilites of this dependency
injection framework.</p>
</div>]]></description>
            <pubDate>Tue, 30 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/01/zend-jquery-enhancements-ajax-forms-tooltip-and-autofill.html</link>
            <guid>http://www.whitewashing.de/2008/12/01/zend-jquery-enhancements-ajax-forms-tooltip-and-autofill.html</guid>
            <title><![CDATA[Zend + jQuery Enhancements: Ajax Forms, Tooltip and Autofill]]></title>
            <description><![CDATA[<div class="section" id="zend-jquery-enhancements-ajax-forms-tooltip-and-autofill">
<h1>Zend + jQuery Enhancements: Ajax Forms, Tooltip and Autofill</h1>
<p>Some weeks ago <a class="reference external" href="http://framework.zend.com">Zend Framework 1.7</a> was
released with the <a class="reference external" href="http://jquery.com">jQuery</a> support I contributed.
What is the essential advantage of using jQuery support in ZF? You can
develop forms with ajax support either by using View Helpers or directly
by the integrated Zend_Form support. The implementation of a DatePicker
or AutoComplete functionality becomes as easy as using 2-3 lines of php
code.</p>
<p>Currently only support for the jQuery UI library is shipped, but you can
easily extend the jQuery support on your own and this blog post will
show you how using three very popular jQuery plugins:
<a class="reference external" href="http://malsup.com/jquery/form/">AjaxForm</a>,
<a class="reference external" href="http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/">Tooltip</a>
and <a class="reference external" href="http://plugins.jquery.com/project/Autofill">AutoFill</a>. This will
be a series of installments, beginning with the first one: AjaxForms</p>
<p>AjaxForm allows you to enhance any form of yours to submit the data with
ajax to the server, so no additional overhead of loading a new page is
necessary. Combining the power of Zend_Form and jQuery’s ajaxForm you
can even go so far as differentiating between successful and
non-validated form submits. We will build a Form Decorator that
integrates the AjaxForm plugin in any of your Zend_Form’s. On submit it
will send the form data to the server via ajax and clears the form
afterwards. Clients that have javascript disabled will work too, the
form is submitted to the server in a standard pre-ajax fashion and
processed that way.</p>
<p>First what we need is obviously the new decorator, we will call it
“My_JQuery_Form_Decorator_AjaxForm” and it will inherit from
Zend_Form_Decorator_Form. What we then realize is, that this is just
using a view helper to render, so what we need additionally is a
“My_JQuery_View_Helper_AjaxForm” that extends from
“Zend_View_Helper_Form”. The code of the view helper will have to
look as follows to fulfil our needs:</p>
<blockquote>
<div><div class="highlight-python"><pre>require_once &quot;Zend/View/Helper/Form.php&quot;;class ZendX_JQuery_View_Helper_AjaxForm extends Zend_View_Helper_Form{  /**   * Contains reference to the jQuery view helper   *   * @var ZendX_JQuery_View_Helper_JQuery_Container   */  protected $jquery;  /**   * Set view and enable jQuery Core and UI libraries   *   * @param Zend_View_Interface $view   * @return ZendX_JQuery_View_Helper_Widget   */  public function setView(Zend_View_Interface $view)  {    parent::setView($view);    $this-&gt;jquery = $this-&gt;view-&gt;jQuery();    $this-&gt;jquery-&gt;enable()           -&gt;uiEnable();    return $this;  }  public function ajaxForm($name, $attribs = null, $content = false, array $options=array())  {    $id = $name;    if(isset($attribs['id'])) {      $id = $attribs['id'];    }    if(!isset($options['clearForm'])) {      $options['clearForm'] = true;    }    if(count($options) &gt; 0) {      require_once &quot;Zend/Json.php&quot;;      $jsonOptions = Zend_Json::encode($options);      // Fix Callbacks if present      if(isset($options['beforeSubmit'])) {        $jsonOptions = str_replace('&quot;beforeSubmit&quot;:&quot;'.$options['beforeSubmit'].'&quot;', '&quot;beforeSubmit&quot;:'.$options['beforeSubmit'], $jsonOptions);      }      if(isset($options['success'])) {        $jsonOptions = str_replace('&quot;success&quot;:&quot;'.$options['success'].'&quot;', '&quot;success&quot;:'.$options['success'], $jsonOptions);      }    } else {      $jsonOptions = &quot;{}&quot;;    }    $this-&gt;jquery-&gt;addOnLoad(sprintf(      '$(&quot;#%s&quot;).ajaxForm(%s)', $id, $jsonOptions    ));    return parent::form($name, $attribs, $content);  }}</pre>
</div>
</div></blockquote>
<p>It takes all the form-tag building of the inherited view helper for
granted and just appends the necessary jQuery code to the jQuery
onLoadActions stack. They will be outputted to the clients browser when
calling &lt;?php $this-&gt;jQuery(); ?&gt; in your layout or view script. Make
sure that you include the jQuery Form plugin in your code, for example
with &lt;?php $view-&gt;jQuery()-&gt;addJavascriptFile(..); &gt;</p>
<p>Programming the decorator becomes a simple trick now:</p>
<blockquote>
<div><div class="highlight-python"><pre>require_once &quot;Zend/Form/Decorator/Form.php&quot;;class My_JQuery_Form_Decorator_AjaxForm extends Zend_Form_Decorator_Form{  protected $_helper = &quot;ajaxForm&quot;;  protected $_jQueryParams = array();  public function getOptions()  {    $options = parent::getOptions();    if(isset($options['jQueryParams'])) {      $this-&gt;_jQueryParams = $options['jQueryParams'];      unset($options['jQueryParams']);      unset($this-&gt;_options['jQueryParams']);    }    return $options;  }  /**   * Render a form   *   * Replaces $content entirely from currently set element.   *   * @param string $content   * @return string   */  public function render($content)  {    $form  = $this-&gt;getElement();    $view  = $form-&gt;getView();    if (null === $view) {      return $content;    }    $helper    = $this-&gt;getHelper();    $attribs    = $this-&gt;getOptions();    $name     = $form-&gt;getFullyQualifiedName();    $attribs['id'] = $form-&gt;getId();    return $view-&gt;$helper($name, $attribs, $content, $this-&gt;_jQueryParams);  }}</pre>
</div>
</div></blockquote>
<p>Now to use either the decorator for your form, or just the view helper
to print your form tag with jQuery code you can invoke:</p>
<blockquote>
<div><div class="highlight-python"><pre>$form-&gt;addPrefixPath('My_JQuery_Form_Decorator', 'My/JQuery/Form/Decorator', 'decorator');$form-&gt;removeDecorator('Form')-&gt;addDecorator(array('AjaxForm', array(  'jQueryParams' =&gt; array(),)));$view-&gt;addHelperPath(&quot;My/JQuery/View/Helper&quot;, &quot;My_JQuery_View_Helper&quot;);$view-&gt;ajaxForm(&quot;formId1&quot;, $attribs, $content, $options);</pre>
</div>
</div></blockquote>
<p>Now we finished up the view side of our script. Assuming that we use the
Form Decorator instead of the View Helper, we can additionally add some
fancy logic and error handling ajax fun to the action controller that is
handling the Zend_Form instance.</p>
<blockquote>
<div><div class="highlight-python"><pre>class IndexController extends Zend_Controller_Action{  public function indexAction()  {    $foo = new MyAjaxTestForm();    try {      if(!$foo-&gt;isValid($_POST)) {        throw new Exception(&quot;Form is not valid!&quot;);      } else {        // do much saving and stuff here        if($this-&gt;getRequest()-&gt;isXmlHttpRequest()) {          $this-&gt;_helper-&gt;json(array(&quot;success&quot; =&gt; &quot;SUCCESSMESSAGEHERE&quot;));        }      }    } catch(Exception $e) {      if($this-&gt;getRequest()-&gt;isXmlHttpRequest()) {        $jsonErrors = array();        foreach( ( new RecursiveIteratorIterator(new RecursiveArrayIterator($form-&gt;getMessages())) ) AS $error) {          $jsonErrors[] = $error;        }        $this-&gt;_helper-&gt;json-&gt;sendJson($jsonErrors);      }    }  }}</pre>
</div>
</div></blockquote>
<p>This has to be processed by a callback function of the AjaxForm and
which may for example look like the following which uses a predefined
div box (#formMessages, don’t forget to implement it) to render either
the success or the error messages.</p>
<blockquote>
<div><div class="highlight-python"><pre>$form-&gt;addDecorator(array('AjaxForm', array(  'jQueryParams' =&gt; array(    'success' =&gt; &quot;formCallback1&quot;,   ),)));$view-&gt;jQuery()-&gt;addJavascript('function formCallback1(data) {  if(data.errors) {    $(&quot;#formMessages&quot;).append(&quot;&lt;ul&gt;&quot;);    for each(var item in data.errors) {      $(&quot;#formMessages&quot;).append(&quot;&lt;li&gt;&quot;+item+&quot;&lt;/li&gt;&quot;);    }    $(&quot;#formMessages&quot;).append(&quot;&lt;/ul&gt;&quot;);  } else {    $(&quot;#formMessages&quot;).html(data.success);  }}');</pre>
</div>
</div></blockquote>
<p>This seems very complex, but you could include that javascript code into
the AjaxForm decorator and implement an Action Helper to do the action
controller side of the stuff. This will be an exercise for a future
post.</p>
<p>AutoFill and Tooltip extensions will be topic of the next installments
of this series, so be aware of new content soonish.</p>
</div>]]></description>
            <pubDate>Mon, 01 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/18/dependecy-injection-the-juicy-way.html</link>
            <guid>http://www.whitewashing.de/2008/12/18/dependecy-injection-the-juicy-way.html</guid>
            <title><![CDATA[Dependency Injection the juicy way]]></title>
            <description><![CDATA[<div class="section" id="dependency-injection-the-juicy-way">
<h1>Dependency Injection the juicy way</h1>
<p>I have written on dependency injection before and <a class="reference external" href="http://www.whitewashing.de/blog/articles/83">came up with a
solution for PHP via interface
injection</a>. Thinking
about it twice I didn’t like it very much. Its too much overkill that
you have to implement all setter methods again and again.</p>
<p>Still dependency injection is the way to write good, testable and easily
exchanged and re-wired object graphs. I tried to do lots of dependency
injection via constructor lately and realized that it pollutes my
constructors when my object graph is too deep.</p>
<p>An example: When I setup my database connection in the bootstrap file
and encapsulate it in my model creation factory object, i have to insert
the model factory through the configuration into the dispatcher into the
different controllers and views to be accessible in the MVC pattern. The
model factory has to walk 3 nodes in the object graph without being used
at all in the “higher” steps. This creates very unnecessary
dependencies.</p>
<p>I came across <a class="reference external" href="http://misko.hevery.com/">Misko Hevery</a>‘s Blog, which
rocks. There are also some <a class="reference external" href="http://www.youtube.com/results?search_query=misko+hevery&amp;search_type=&amp;aq=f">great Google Tech Talks by
him</a>,
where he argues in favour of dependency injection and debunks singletons
as being evil (he does that on his blog too). From there I learnt about
<a class="reference external" href="http://code.google.com/p/google-guice/">Guice</a>, a dependency
injection framework for Java by Google.</p>
<p>What I like about Guice: Its easy to use and its immediately obvious to
someone without experience, why it works so good and you don’t have to
hand down objects deep down the object graph. I cloned the basic
functionality for PHP and an example would work as follows.</p>
<p>We first have to implement a <strong>module</strong>, which defines which concrete
implementation should be injected as a placeholder for which interface.</p>
<blockquote>
<div><div class="highlight-python"><pre>class ServiceModule implements Module{ public function configure(Binder $b) {  $b-&gt;bind(&quot;Service&quot;)-&gt;to(&quot;ConcreteService&quot;);  $b-&gt;bind(&quot;Add&quot;)-&gt;to(&quot;ConcreteAdd&quot;);  $b-&gt;bind(&quot;Sub&quot;)-&gt;to(&quot;ConcreteSub&quot;); }}</pre>
</div>
</div></blockquote>
<p>We can now use this module to instantiate an injector object:</p>
<blockquote>
<div><div class="highlight-python"><pre>$injector = new Injector( new ServiceModule() );$service = $injector-&gt;getInstance(&quot;Service&quot;);</pre>
</div>
</div></blockquote>
<p>Given that the constructor of <strong>ConcreteService</strong> would expect an Add
and a Sub object, the Injector would realize this and instantiate the
concrete implementations <strong>ConcreteAdd</strong> and <strong>ConcreteSub</strong> and inject
them into the constructor.</p>
<p>What makes this dependency injection so simple and great to use? You can
instantiate an injector everywhere in your code and just have to
configure it using the additional module implementation. This way you
don’t have to make sure that you pass down the dependency injection
container from the bootstrap into all nodes of the application. You can
also easily work with many frameworks and still be able to use
dependency injection without having to hack the whole core of the
framework.</p>
<p>My guice clone does more. It allows to pass down additional non-object
arguments into constructors, even for object dependencies. It offers a
<strong>Provider</strong> interface to be able to wrap adapters around your already
existing ServiceLocator or Registry objects. But its reflection
capabilities have to be extended to docblock comments, so that better
dependency detection is possible.</p>
<p>Because using dependency injection with only this little example I will
refrain from releasing the source code yet. I have to provide some
useful documentation for it to be of use to anyone.</p>
</div>]]></description>
            <pubDate>Thu, 18 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/03/ezcomponents-view-handler-for-zend-pdf.html</link>
            <guid>http://www.whitewashing.de/2008/12/03/ezcomponents-view-handler-for-zend-pdf.html</guid>
            <title><![CDATA[ezComponents View Handler for Zend_Pdf]]></title>
            <description><![CDATA[<div class="section" id="ezcomponents-view-handler-for-zend-pdf">
<h1>ezComponents View Handler for Zend_Pdf</h1>
<p><a class="reference external" href="http://www.whitewashing.de/blog/article/93">My previous posting</a>
discussed different view handlers based on routing information. One
example was the PDF View which was implemented rather hackish through
overwriting the <strong>createResponseBody()</strong> function of <strong>ezcMvcView</strong>.
<a class="reference external" href="http://www.derickrethans.nl/">Derick</a> told me the way to go would be
writing my own PDF view handler. Since this is a rather lengthy topic I
created this new post that only discusses using
<a class="reference external" href="http://framework.zend.com/manual/en/zend.pdf.html">Zend_Pdf</a> as a
View Handler in the new <a class="reference external" href="http://www.ezcomponents.org">ezComponents
MvcTools</a>.</p>
<p>The code for the View Handler would look like the following:</p>
<blockquote>
<div><div class="highlight-python"><pre>abstract class myPdfViewHandler implements ezcMvcViewHandler
{
    /**
     * Contains the zone name
     *
     * @var string
     */
    protected $zoneName;

    /**
     * Contains the variables that will be available in the template.
     *
     * @var array(mixed)
     */
    protected $variables = array();

    /**
     * Pdf object to be rendered.
     *
     * @var Zend_Pdf
     */
    protected $pdf;

    /**
     * Creates a new view handler, where $zoneName is the name of the block and
     * $templateLocation the location of a view template.
     *
     * @var string $zoneName
     * @var string $templateLocation
     */
    public function __construct( $zoneName, $templateLocation = null )
    {
        $this-&gt;zoneName = $zoneName;
    }

    /**
     * Adds a variable to the template, which can then be used for rendering
     * the view.
     *
     * @param string $name
     * @param mixed $value
     */
    public function send( $name, $value )
    {
        $this-&gt;variables[$name] = $value;
    }

    /**
     * Processes the template with the variables added by the send() method.
     * The result of this action should be retrievable through the getResult() method.
     */
    public function process( $last )
    {
        // template method
    }

    /**
     * Returns the value of the property $name.
     *
     * @throws ezcBasePropertyNotFoundException if the property does not exist.
     * @param string $name
     * @ignore
     */
    public function __get( $name )
    {
        return $this-&gt;variables[$name];
    }

    /**
     * Returns true if the property $name is set, otherwise false.
     *
     * @param string $name
     * @return bool
     * @ignore
     */
    public function __isset( $name )
    {
        return array_key_exists( $name, $this-&gt;variables );
    }

    /**
     * Returns the name of the template, as set in the constructor.
     *
     * @return string
     */
    public function getName()
    {
        return $this-&gt;zoneName;
    }

    /**
     * Returns the result of the process() method.
     *
     * @return mixed
     */
    public function getResult()
    {
        if($this-&gt;pdf instanceof Zend_Pdf) {
            return $this-&gt;pdf-&gt;render();
        } else {
            throw new Exception(&quot;Could not render PDF.&quot;);
        }
    }
}</pre>
</div>
</div></blockquote>
<p>Now you would implement a concrete PDF view handler by extending
myPdfViewHandler.</p>
<blockquote>
<div><div class="highlight-python"><pre>class myConcretePdfViewHandler extends myPdfViewHandler {
    public function process( $last )
    {
        $pdf = new Zend_Pdf();
        // do concrete PDF drawing stuff here

        // save PDF here, will be rendered in getResult()
        $this-&gt;pdf = $pdf;
    }
}</pre>
</div>
</div></blockquote>
<p>And your <strong>ezcMvcView</strong> implementation will make of <strong>createZones()</strong>
and look like the following:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myPdfView extends ezcMvcView {
    function createZones( $layout )
    {
        $zones = array();
        // A decision which concrete Pdf Handler should be used would be decided on here.
        $zones[] = new myConcretePdfViewHandler( 'concreteA' );
        return $zones;
    }
}</pre>
</div>
</div></blockquote>
<p>There you go!</p>
</div>]]></description>
            <pubDate>Wed, 03 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/03/ezcomponents-2008-2-beta-mvc-separation-for-win.html</link>
            <guid>http://www.whitewashing.de/2008/12/03/ezcomponents-2008-2-beta-mvc-separation-for-win.html</guid>
            <title><![CDATA[ezComponents 2008.2 Beta - Mvc separation for win]]></title>
            <description><![CDATA[<div class="section" id="ezcomponents-2008-2-beta-mvc-separation-for-win">
<h1>ezComponents 2008.2 Beta - Mvc separation for win</h1>
<p><a class="reference external" href="http://www.whitewashing.de/blog/articles/88">I have written</a> on the
<a class="reference external" href="http://ezcomponents.org">new ezComponents MvcTools</a> component before
already. Just yesterday the beta of this component was released with the
<a class="reference external" href="http://ezcomponents.org/resources/news/news-2008-12-01">general beta of the 2008.2
version</a> of
ezComponents. Several bugfixes and enhancements were included into the
MvcTools which make it a perfect component for any Mvc based
application.</p>
<p>I reviewed lots of the code myself and can only say i love the beauty of
the code. Its very simple but by default the most powerful mvc solution
in the PHP market. People working with unittests will like it very much,
since all the parts are perfectly separated from each other allowing to
test controllers, views, routers and filters in complete separation.</p>
<p>To show one very simple example howto benefit of the separation of view
and controllers. If we need a view in both html and pdf, this should
generally make no difference for the controller. We add two routes, one
for the pdf one for the html view that execute the same controller and
action:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myRouter extends ezcMvcRouter{ public function createRoutes() {  return array(   new ezcMvcRailsRoute( '/pdf', 'SomeController', 'index'),   new ezcMvcRailsRoute( '/', 'SomeController', index' ),  ); }}class SomeController extends ezcMvcController{ public function doIndex() {  $result = new ezcMvcResult();  $result-&gt;variables['items'] = Model::retrieveLotsOfItems();  return $result; }}</pre>
</div>
</div></blockquote>
<p>Now howto decide between PDF and Html view? We use the createView method
of our dispatcher configuration, but we still only need the http
response writer, nothing more.</p>
<blockquote>
<div><div class="highlight-python"><pre>class myMvcConfiguration implements ezcMvcDispatcherConfiguration { [...] function createView( ezcMvcRoutingInformation $routeInfo, ezcMvcRequest $request, ezcMvcResult $result ) {  if(strstr($routeInfo-&gt;matchedRoute, &quot;/pdf&quot;)) {   return new myHtmlView( $request, $result );  } else {   return new myPdfView( $request, $result );  } } function createResponseWriter( ezcMvcRoutingInformation $routeInfo, ezcMvcRequest $request, ezcMvcResult $result, ezcMvcResponse $response ) {  return new ezcMvcHttpResponseWriter( $response ); } [...]}</pre>
</div>
</div></blockquote>
<p>Now both <strong>myHtmlView</strong> and <strong>myPdfView</strong> can create their
ezcMvcResponse objects that fill the response body depending on their
type. Please note that overwriting createResponseBody() in myPdfView is
a shortcut that circumvents me having to write a new PDF View Handler
(which would be the way to go).</p>
<blockquote>
<div><div class="highlight-python"><pre>class myHtmlView extends ezcMvcView { function createZones( $layout ) {  $zones = array();   $zones[] = new ezcMvcPhpViewHandler( 'content', '../templates/index.phtml' );  $zones[] = new ezcMvcPhpViewHandler( 'page_layout', '../templates/layout.phtml' );  return $zones; }}class myPdfView extends ezcMvcView { function createZones() {  // empty, abstract method that has to be defined. } function createResponseBody() {  // Set PDF Content-Type Response Header  $this-&gt;result-&gt;content-&gt;type = &quot;application/pdf&quot;;   $pdf = new Zend_Pdf();  // do pdf stuff  return $pdf-&gt;render(); }}</pre>
</div>
</div></blockquote>
<p>Now all the the logic that is potentially in the controller is completely
separated from the view handling that may depend on the routing
information not on the controller. And views can be tested separately
from the controller result. Testability is very high.</p>
</div>]]></description>
            <pubDate>Wed, 03 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/04/rest-and-ajax-aware-controllers-in-ezcmvctools.html</link>
            <guid>http://www.whitewashing.de/2008/12/04/rest-and-ajax-aware-controllers-in-ezcmvctools.html</guid>
            <title><![CDATA[REST and Ajax Aware controllers in ezcMvcTools]]></title>
            <description><![CDATA[<div class="section" id="rest-and-ajax-aware-controllers-in-ezcmvctools">
<h1>REST and Ajax Aware controllers in ezcMvcTools</h1>
<p>There are essentially two major different ways to implement a restful
application using a web framework. You either implement a router that
routes to different controller actions based on the HTTP method used on
a requested resource. This is the fancy way, which sadly is not always
so practical because many browsers do not support sending more than GET
and POST requests. The other way would be to define suburls of a
resource such as <strong>/user/1/delete</strong> for the resource <strong>/user/1</strong> and
take GET a a request for deleting and POST for the confirmation of the
delete.</p>
<p>ezcMvcTools HTTP Request Parser and routing mechanisms currently offer
no real help to decide on this issues, but its easy to extend this
missing functionality. What we first add are simple checks of the
current http request method. We extend <strong>ezcMvcHttpRequestParser</strong> which
will return a derived <strong>ezcMvcRequest</strong> object that implements 7 new
methods: isPost(), isGet(), isDelete(), isPut(), isXmlHttpRequest(),
isMethod() and getMethod(). These methods can now be easily used on the
request object to determine which action will be undertaken:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myMvcRequest extends ezcMvcRequest{  public function isPost()  {    return $this-&gt;isMethod(&quot;POST&quot;);  }  public function isGet()  {    return $this-&gt;isMethod(&quot;GET&quot;);  }  public function isPut()  {    return $this-&gt;isMethod(&quot;PUT&quot;);  }  public function isDelete()  {    return $this-&gt;isMethod(&quot;DELETE&quot;);  }  public function isXmlHttpRequest()  {    if(isset($this-&gt;raw['HTTP_X_REQUESTED_WITH'])      &amp;&amp; strtolower($this-&gt;raw['HTTP_X_REQUESTED_WITH']) == &quot;xmlhttprequest&quot;) {      return true;    }    return false;  }    public function getMethod()  {    if(isset($this-&gt;raw['REQUEST_METHOD']))      return strtolower($this-&gt;raw['REQUEST_METHOD']);    }    return false;  }  public function isMethod($method)  {    if(isset($this-&gt;raw['REQUEST_METHOD']) &amp;&amp;       $this-&gt;getMethod() == strtolower($method)) {      return true;    }    return false;  }}class myMvcHttpRequestParser extends ezcMvcHttpRequestParser{  /**   * Uses the data from the superglobals.   *   * @return ezcMvcRequest   */  public function createRequest()  {    $this-&gt;request = new myMvcRequest;    $this-&gt;processStandardHeaders();    $this-&gt;processAcceptHeaders();    $this-&gt;processUserAgentHeaders();    $this-&gt;processFiles();    $this-&gt;processAuthVars();    $this-&gt;request-&gt;raw = &amp;$_SERVER;    return $this-&gt;request;  }}</pre>
</div>
</div></blockquote>
<p>This helps us to implement simple decision mechanisms in a single
controller action that takes both POST and GET requests. From the point
separation of concerns this is not a good design decision. We need
routes that can point to different controller actions based on their
request method, so that two requests <strong>GET /user/1/delete</strong> and <strong>POST
/user/1/delete</strong> lead to different methods, for example
<strong>userController::doDeleteDialog</strong> and <strong>userController::doDelete</strong>. We
will simply extend the <strong>ezcMvcRailsRoute</strong> to support decision based on
http request methods:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myMvcRestRoute extends ezcMvcRailsRoute{  protected $method;  public function __construct( $method, $pattern, $controllerClassName, $action = null, array $defaultValues = array() )  {    $this-&gt;method = $method;    parent::__construct($pattern, $controllerClassName, $action, $defaultValues);  }  public function matches( ezcMvcRequest $request )  {    if(strtolower($this-&gt;method) == strtolower($request-&gt;raw['REQUEST_METHOD'])) {      return parent::matches($request);    }    return null;  }}</pre>
</div>
</div></blockquote>
<p>This very simple extension is independent of the advanced request parser
given above, so you could use it separately. In the light of our delete
user example, you would use the new router in the following way:</p>
<blockquote>
<div><div class="highlight-python"><pre>class myRouter extends ezcMvcRouter{  public function createRoutes()  {    return array(      new myMvcRestRoute( 'GET', '/users/:id/delete', 'UserController', 'deleteDialog' ),      new myMvcRestRoute( 'POST', '/users/:id/delete', 'UserController', 'delete' ),    );  }}</pre>
</div>
</div></blockquote>
<p>We have now simple rest route support in our ezcMvcTools application.</p>
</div>]]></description>
            <pubDate>Thu, 04 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/12/12/bad-news-jquery-ui-1-6-ships-without-spinner-and-autocomplete.html</link>
            <guid>http://www.whitewashing.de/2008/12/12/bad-news-jquery-ui-1-6-ships-without-spinner-and-autocomplete.html</guid>
            <title><![CDATA[Bad news: jQuery UI 1.6 ships without Spinner and AutoComplete]]></title>
            <description><![CDATA[<div class="section" id="bad-news-jquery-ui-1-6-ships-without-spinner-and-autocomplete">
<h1>Bad news: jQuery UI 1.6 ships without Spinner and AutoComplete</h1>
<p>The jQuery UI team <a class="reference external" href="http://blog.jquery.com/2008/12/11/whats-up-with-jquery-ui/">announced yesterday on its
blog</a> that
<a class="reference external" href="http://ui.jquery.com">jQuery UI 1.6</a> will not be shipped with
AutoComplete and Spinner Plugin support. No further delay, for the
original august 2008 estimated release, is wanted.</p>
<p>This brings about a problem on
<a class="reference external" href="http://framework.zend.com/manual/en/zendx.jquery.html">ZendX_JQuery</a>.
All view helpers and decorators that depend on AutoComplete and Spinner
Plugins can only be run with SVN trunk or 1.6 release candidates, which
have known bugs and problems.</p>
<p>I am adding a compatibility table to the ZendX jQuery manual today that
will make its way to the manual of the 1.7.2 release. This will
hopefully help and guide everyone to the correct dependencies.</p>
</div>]]></description>
            <pubDate>Fri, 12 Dec 2008 00:00:00 +0100</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/14/jquery-helper-what-is-to-include.html</link>
            <guid>http://www.whitewashing.de/2008/07/14/jquery-helper-what-is-to-include.html</guid>
            <title><![CDATA[jQuery Helper - What is to include?]]></title>
            <description><![CDATA[<div class="section" id="jquery-helper-what-is-to-include">
<h1>jQuery Helper - What is to include?</h1>
<p>I took some time in the last days to develop the concept for a possible
jQuery View Helper that could pass the integration into the <a class="reference external" href="http://framework.zend.com">ZF
Core</a>. Since
<a class="reference external" href="http://www.jquery.com">jQuery</a> is organized somewhat different than
Dojo is, its possible implementation for ZF will differ.</p>
<p>The jQuery Helper itself will manage inclusion of jQuery javascript
files and the base library, much like the Dojo component works (Using
the Google CDN). On top of this simple Helpers should mimic $.get,
$.post, $.load and $.getJSON in a simple way, so that with a simple
function call you can generate an XmlHttpRequest that updates a
specified part of the DOM (via injection). (See: <a class="reference external" href="http://book.cakephp.org/view/208/ajax">CakePHP
Ajax</a>)</p>
<p>Problematic are the next ideas: Additional Helpers will allow to
specify the <a class="reference external" href="http://ui.jquery.com">jQuery UI Library</a> components
(DatePicker, Sortables, Draggable, Dropable..), <a class="reference external" href="http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/">jQuery
Autocomplete</a>
or <a class="reference external" href="http://malsup.com/jquery/form/">jQuery Form</a> (AjaxForm and
AjaxSubmit). These libraries need additional javascript content to be
downloaded and implemented in the Zend Framework project. There
currently exists no way to implement them using a CDN. Therefore any
documentation must clearly specify which additional content has to be
installed and how. The helpers will have to be general enough to support
this.</p>
<p>My proposal is currently in the workings and will be on the ZF Wiki in
the next couple of hours.</p>
</div>]]></description>
            <pubDate>Mon, 14 Jul 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/22/multidimensional-array-via-spl.html</link>
            <guid>http://www.whitewashing.de/2008/07/22/multidimensional-array-via-spl.html</guid>
            <title><![CDATA[Multidimensional Array via SPL]]></title>
            <description><![CDATA[<div class="section" id="multidimensional-array-via-spl">
<h1>Multidimensional Array via SPL</h1>
<p>Per default any implementation of ArrayObject does not allow to use the
object as multidimensional array. This snippet here implements the
support:</p>
<div class="highlight-php"><div class="highlight"><pre><span class="x">class ArrayMultiObject extends ArrayObject</span>
<span class="x">{</span>
<span class="x">    function __construct($array, $flags = 0, $iterator_class = &quot;ArrayIterator&quot;)</span>
<span class="x">    {</span>
<span class="x">        $objects = array();</span>
<span class="x">        foreach($array AS $key =&gt; $value) {</span>
<span class="x">            if(is_array($value)) {</span>
<span class="x">                $objects[$key] = new ArrayMultiObject($value, $flags, $iterator_class);</span>
<span class="x">            } else {</span>
<span class="x">                $objects[$key] = $value;</span>
<span class="x">            }</span>
<span class="x">        }</span>

<span class="x">        parent::__construct($objects, $flags, $iterator_class);</span>
<span class="x">    }</span>

<span class="x">    public function offsetSet($name, $value)</span>
<span class="x">    {</span>
<span class="x">        if(is_array($value)) {</span>
<span class="x">            $value = new ArrayMultiObject($value);</span>
<span class="x">        }</span>

<span class="x">        return parent::offsetSet($name, $value);</span>
<span class="x">    }</span>
<span class="x">}</span>
</pre></div>
</div>
</div>]]></description>
            <pubDate>Tue, 22 Jul 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/17/zf-jquery-helper-first-prototype-ready.html</link>
            <guid>http://www.whitewashing.de/2008/07/17/zf-jquery-helper-first-prototype-ready.html</guid>
            <title><![CDATA[ZF jQuery Helper - First Prototype Ready]]></title>
            <description><![CDATA[<div class="section" id="zf-jquery-helper-first-prototype-ready">
<h1>ZF jQuery Helper - First Prototype Ready</h1>
<p>I checked in the first implementation of my jQuery Helper into my <a class="reference external" href="http://www.beberlei.de/dev/svn">dev
svn</a>. It follows my suggested
<a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/ZendX_JQuery_View_Helper_JQuery+-+Benjamin+Eberlei">proposal in the Zend Framework Dev
Wiki</a>
and implements all the advertised features. I also implemented 2 demos
that nicely present the functionality.</p>
<p>Please test and comment!</p>
</div>]]></description>
            <pubDate>Thu, 17 Jul 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/21/zend-dojo-and-the-django-template-language.html</link>
            <guid>http://www.whitewashing.de/2008/07/21/zend-dojo-and-the-django-template-language.html</guid>
            <title><![CDATA[Zend, Dojo and the Django Template Language]]></title>
            <description><![CDATA[<div class="section" id="zend-dojo-and-the-django-template-language">
<h1>Zend, Dojo and the Django Template Language</h1>
<p>With the Zend Framework <a class="reference external" href="http://www.nabble.com/1.6-RC1-Schedule-tp18538148p18538148.html">nearing its 1.6
release</a>
and full <a class="reference external" href="http://www.dojotoolkit.org">Dojo Toolkit</a> support I took
some time to look up what Dojo is actually capable of. I found the
<a class="reference external" href="http://dojotoolkit.org/book/dojo-book-0-9/part-5-dojox/dojox-dtl">DojoX Django Template
Language</a>
extension and remembered my neighbor talking about why Python + Django
is so much better than PHP with any other framework. So I digged into
the <a class="reference external" href="http://www.djangoproject.com/documentation/templates_python/">Django template
language</a>
and found that it is quite awesome.</p>
<p>Variable filtering and evaluation looks almost like Smarty the syntax
being {{var.key|filter1|filter2:”arg1”:”arg2”}}. The logical syntax is
quite different though, taking an somehow object oriented view on
templates you can extend an existing template and override specific
parts with your more special implementation. Have a look at the
following two snippets:</p>
<blockquote>
<div><div class="highlight-python"><pre>This is an example of Django template inheritance:

{% block helloworld %}Hello World!{% endblock %}</pre>
</div>
<div class="highlight-python"><pre>{% extends &quot;base.html&quot; %}

{%block helloworld %}Hello World for Object Oriented Views!{% endblock %}</pre>
</div>
</div></blockquote>
<p>What does Django do with this second template when rendering? It
realizes it inherits logic from a parent template and substitutes all
special blocks for the parent ones. With a little object oriented
background you can guess the result looks like this:</p>
<blockquote>
<div><div class="highlight-python"><pre>This is an example of Django template inheritance:

Hello World for Object Oriented Views!</pre>
</div>
</div></blockquote>
<p>So what was all the talking about Dojo being able to parse this kind of
templates? If you envision a helper component that would function like
this: 1.) make an ajax request to $url 2.) retrieve json object from the
controller 3.) render json object with $template into container
$container. The helper would know that the template is needed in this
HTML response and appends it to the Dojo Helper output. A link would be
generated performing steps 1 and 2, handing over the json data to the
template and render the output. What do you get? Templates that can be
used Client and Server side.</p>
<p>For example on rendering the view of your blog you can send all the
comments using a specific comment building Django template script.
Additionally you can also use the same template to render any new
comment to the comment list using via an ajax form submit, returning the
(model or form) filtered data via JSON and appending it to the comment
list using the DojoX DTL parser. For non-JS browsers you can always use
a &lt;noscript&gt; variant to render the templates completely server-side.</p>
<p>This generally being a cool idea since it makes developing applications
with AJAX technology very easy I began to port the DTL to the Zend
Framework and the whole weekend later I got a working implementation
that supports at least the “extends”, “for”, “include”, and “comment”
tags. As a next task I will implement the helper for DojoX DTL and will
report back on my efforts.</p>
</div>]]></description>
            <pubDate>Mon, 21 Jul 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/12/discussing-a-jquery-helper-for-zend-framework.html</link>
            <guid>http://www.whitewashing.de/2008/07/12/discussing-a-jquery-helper-for-zend-framework.html</guid>
            <title><![CDATA[Discussing a jQuery Helper for Zend Framework]]></title>
            <description><![CDATA[<div class="section" id="discussing-a-jquery-helper-for-zend-framework">
<h1>Discussing a jQuery Helper for Zend Framework</h1>
<p>Yesterday I had some time to test Matthews <a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_View_Helper_Dojo">Dojo View
Helper</a>
and the Zend_Dojo_Form component. At a first glance the implementation
looks great and can almost instantly generate you a very nice form with
all the possible Dijit form extensions that
<a class="reference external" href="http://dojotoolkit.org/">Dojo</a> has to offer.</p>
<p>If one were to refactor the Dojo Component to allow for
<a class="reference external" href="http://www.jquery.com">jQuery</a> elements one bigger problem appears.
Dojo has a CDN (Content Distribution Network) for all its components,
that is, the Zend Dojo components can load all javascript and css files
from a distant server. JQuery can only offer its main library to be
loaded from a CDN. All additional components, for example the jQuery
DatePicker, have to be installed locally. This significantly reduces the
possibility for rapid development of Javascript/Ajax/Form components
with jQuery and Zend Framework.</p>
<p>One could offer a complete dependency downloadable archive with all the
CSS, Javascript and Images inside, but this would be very complex to
maintain. Looking at the future Zend Tool capabilities one possibility
would be to offer a download client for all the relevant jQuery plugins,
but there would have to be a man-middle-server that maintains the most
up to date locations of all the plugins, which also has to be
maintained. Does anybody have a better solution to solve this problem?
Perhaps the jQuery Team needs to be made aware that they need a CDN for
their most stable plugins.</p>
<p>Abstracting from the CDN problem, I implemented a simple jQuery View
Helper (mostly copy paste and simple rewrites from Matthews Dojo
component) and a HtmlElement Form Helper which constructs a Date-Picker
from within the template. This is very easy to use and looks great. In
the next days I will add further helpers for the jQuery plugins I use in
my day to day work live and hope to present a demo. I might even opting
for a jQuery proposal aiming at inclusion in the Zend Extras Library.</p>
<p><strong>Update:</strong> I got a <a class="reference external" href="http://groups.google.com/group/jquery-dev/browse_thread/thread/aec0d89b97a95880">reply on the jQuery mailing
list</a>
stating that a CDN is planned for the jQuery UI library. Sadly this does
not include plugins for which one might desperately need a View Helper
except for maybe the Date Picker. I will post further comments on this
issue in the near future.</p>
</div>]]></description>
            <pubDate>Sat, 12 Jul 2008 00:00:00 +0200</pubDate>
        </item>
        <item>
            <link>http://www.whitewashing.de/2008/07/24/finished-first-django-template-language-port-to-php-zf.html</link>
            <guid>http://www.whitewashing.de/2008/07/24/finished-first-django-template-language-port-to-php-zf.html</guid>
            <title><![CDATA[Finished first Django Template Language Port to PHP + ZF]]></title>
            <description><![CDATA[<div class="section" id="finished-first-django-template-language-port-to-php-zf">
<h1>Finished first Django Template Language Port to PHP + ZF</h1>
<p>Today I finished the first almost complete <a class="reference external" href="http://www.djangoproject.com">Django Template
Language</a> Clone for PHP implementing the
<a class="reference external" href="http://framework.zend.com">Zend Framework</a> View Interface. <a class="reference external" href="http://framework.zend.com/wiki/display/ZFPROP/Zend_View_Dtl+-+Benjamin+Eberlei">My
proposal</a>
is up and running on the ZF Wiki. The source code can be downloaded from
my <a class="reference external" href="http://www.beberlei.de/dev/svn">svn repository</a>.</p>
</div>]]></description>
            <pubDate>Thu, 24 Jul 2008 00:00:00 +0200</pubDate>
        </item>
    </channel>
</rss>