<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
  <channel>
    <title>Blog entries tagged oop :: mwop.net</title>
    <description>Blog entries tagged oop :: mwop.net</description>
    <pubDate>Wed, 05 Dec 2018 16:26:00 -0600</pubDate>
    <generator>Laminas_Feed_Writer 2 (https://getlaminas.org)</generator>
    <link>https://mwop.net/blog/tag/oop</link>
    <atom:link rel="self" type="application/rss+xml" href="https://mwop.net/blog/tag/oop/rss.xml"/>
    <item>
      <title>Creating Exception types on-the-fly in modern PHP</title>
      <pubDate>Wed, 05 Dec 2018 16:26:00 -0600</pubDate>
      <link>https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html</link>
      <guid>https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>We pioneered a pattern for exception handling for Zend Framework back as we
initially began development on version 2 around seven years ago. The pattern
looks like this:</p>
<ul>
<li>We would create a marker <code>ExceptionInterface</code> for each package.</li>
<li>We would extend <a href="http://php.net/manual/en/spl.exceptions.php">SPL exceptions</a>
and implement the package marker interface when doing so.</li>
</ul>
<p>What this gave users was the ability to catch in three ways:</p>
<ul>
<li>They could catch the most specific exception type by class name.</li>
<li>They could catch all package-level exceptions using the marker interface.</li>
<li>The could catch general exceptions using the associated SPL type.</li>
</ul>


<p>So, as an example:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">try</span> {
    $do-&gt;something();
} <span class="hljs-keyword">catch</span> (MostSpecificException $e) {
} <span class="hljs-keyword">catch</span> (PackageLevelExceptionInterface $e) {
} <span class="hljs-keyword">catch</span> (\RuntimeException $e) {
}
</code></pre>
<p>This kind of granularity is really nice to work with. So nice that some
standards produced by <a href="https://www.php-fig.org/">PHP-FIG</a> now ship them, such as
<a href="https://www.php-fig.org/psr/psr-11/">PSR-11</a>, which ships a
<code>ContainerExceptionInterface</code> and a <code>NotFoundExceptionInterface</code>.</p>
<blockquote>
<p>One thing we've started doing recently as we make packages support only PHP 7
versions is to have the marker <code>ExceptionInterface</code> extend the <code>Throwable</code>
interface; this ensures that implementations <strong>must</strong> be able to be thrown!</p>
</blockquote>
<p>So, what happens when you're writing a one-off implementation of something that
is expected to throw an exception matching one of these interfaces?</p>
<p>Why, use an anonymous class, of course!</p>
<p>As an example, I was writing up some documentation that illustrated a custom
<code>ContainerInterface</code> implementation today, and realized I needed to throw an
exception at one point, specifically a <code>Psr\Container\NotFoundExceptionInterface</code>.
I wrote up the following snippet:</p>
<pre><code class="language-php hljs php" data-lang="php">$message = sprintf(<span class="hljs-comment">/* ... */</span>);
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-class"><span class="hljs-keyword">class</span>($<span class="hljs-title">message</span>) <span class="hljs-keyword">extends</span> <span class="hljs-title">RuntimeException</span> <span class="hljs-keyword">implements</span>
    <span class="hljs-title">NotFoundExceptionInterface</span> </span>{
};
</code></pre>
<p>Done!</p>
<p>This works because <code>RuntimeException</code> takes a message as the first
constructor argument; by extending that class, I gain that behavior. Since
<code>NotFoundExceptionInterface</code> is a marker interface, I did not need to add any
additional behavior, so this inline example works out-of-the-box.</p>
<p>What else are <em>you</em> using anonymous classes for?</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html">Creating Exception types on-the-fly in modern PHP</a> was originally
    published <time class="dt-published" datetime="2018-12-05T16:26:00-06:00">5 December 2018</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>OpenShift, Cron, and Naked Domains</title>
      <pubDate>Sun, 30 Dec 2012 09:52:00 -0600</pubDate>
      <link>https://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html</link>
      <guid>https://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>As an experiment, I migrated my website over to
<a href="http://openshift.redhat.com">OpenShift</a> yesterday. I've been hosting a
pastebin there already, and have found the service to be both straightforward
and flexible; it was time to put it to a more thorough test.</p>
<p>In the process, I ran into a number of interesting issues, some of which took
quite some time to resolve; this post is both to help inform other potential
users of the service, as well as act as a reminder to myself.</p>


<h2>Cron</h2>
<p>OpenShift offers a <a href="http://en.wikipedia.org/wiki/Cron">Cron</a> cartridge, which I
was excited to try out.<sup id="ref-1"><a href="#f1">1</a></sup></p>
<p>The basics are quite easy. In your repository's <code>.openshift</code> directory is a
<code>cron</code> subdirectory, further divided into <code>minutely</code>, <code>hourly</code>, <code>daily</code>,
<code>weekly</code>, and <code>monthly</code> subdirectories. You drop a script you want to run into
one of these directories, and push your changes upstream.</p>
<p>The problem is: what if I want a job to run at a specific time daily? or on the
quarter hour? or on a specific day of the week?</p>
<p>As it turns out, you can manage all of the above, just not quite as succinctly
as you would in a normal crontab. Here, for example, is a script that I run at
5AM daily; I placed it in the <code>hourly</code> directory so that it can test more
frequently:</p>
<pre><code class="language-bash hljs bash" data-lang="bash"><span class="hljs-meta">#!/bin/bash</span>
<span class="hljs-keyword">if</span> [ `date +%H` == <span class="hljs-string">"05"</span> ]
<span class="hljs-keyword">then</span>
    (
        <span class="hljs-built_in">export</span> PHP=/usr/<span class="hljs-built_in">local</span>/zend/bin/php ;
        <span class="hljs-built_in">cd</span> <span class="hljs-variable">$OPENSHIFT_REPO_DIR</span> ; 
        <span class="hljs-variable">$PHP</span> public/index.php phlycomic fetch all ; 
        <span class="hljs-variable">$PHP</span> public/index.php phlysimplepage cache clear --page=pages/comics 
    )
<span class="hljs-keyword">fi</span>
</code></pre>
<p>And here's one that runs on the quarter-hour, placed in the <code>minutely</code>
directory:</p>
<pre><code class="language-bash hljs bash" data-lang="bash"><span class="hljs-meta">#!/bin/bash</span>
MINUTES=`date +%M`

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-string">"00"</span> <span class="hljs-string">"15"</span> <span class="hljs-string">"30"</span> <span class="hljs-string">"45"</span>;<span class="hljs-keyword">do</span>
    <span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$MINUTES</span>"</span> == <span class="hljs-string">"<span class="hljs-variable">$i</span>"</span> ];<span class="hljs-keyword">then</span>
        (
            <span class="hljs-built_in">export</span> PHP=/usr/<span class="hljs-built_in">local</span>/zend/bin/php ;
            <span class="hljs-built_in">cd</span> <span class="hljs-variable">$OPENSHIFT_REPO_DIR</span> ;
            <span class="hljs-variable">$PHP</span> public/index.php githubfeed fetch 
        )
    <span class="hljs-keyword">fi</span>
<span class="hljs-keyword">done</span>
</code></pre>
<p>The point is that if you need more specificity, push the script into the next
more specific directory, and test against the time of execution.</p>
<h2>Naked Domains</h2>
<p>Naked domains are domains without a preceding subdomain. In my case, this means
&quot;mwop.net&quot;, vs. &quot;www.mwop.net&quot;.</p>
<p>The problem that cloud hosting presents is that the IP address on which you are
hosted can change at any time, for a variety of reasons. As such, you typically
cannot use DNS A records to point to your domain; the recommendation is to use
a CNAME record that points the domain to a &quot;virtual&quot; domain registered with
your cloud hosting provider.</p>
<p>However, most domain registrars and DNS providers do not let you do this for a
naked domain, particularly if you also have MX or other records associated with
that naked domain.</p>
<p>Some registrars will allow you to forward the A record to a subdomain. I tried
this, but had limited success; I personally found that I ended up in an
infinite loop situation when doing the DNS lookup.</p>
<p>Another solution is to have a redirect in place for your naked domain to the
subdomain, which can then be a CNAME record. Typically, this would require you
have a web server under your control with a fixed IP that then simply redirects
to the subdomain. Fortunately, there's an easier solution:
<a href="http://wwwizer.com/naked-domain-redirect">wwwizer</a>. You simply point your
naked domain A record to the wwwizer IP address, and they will do a redirect to
your <code>www</code> subdomain.</p>
<p>I implemented wwwizer on my domain (which is why you'll see &quot;www.mwop.net&quot; in
your location bar), and it's been working flawlessly since doing so.</p>
<h4>Private repositories</h4>
<p>I keep my critical site settings in a private repository, which allows me to
version them while keeping the credentials they hold out of the public eye.
This means, however, that I need to use
<a href="https://help.github.com/articles/managing-deploy-keys">GitHub deploy keys</a> on
my server in order to retrieve changes.</p>
<p>This was simple enough: I created an <code>ssh</code> subdirectory in my
<code>$OPENSHIFT_DATA_DIR</code> directory, and generated a new SSH keypair.</p>
<p>The problem was telling SSH to <em>use</em> this key when fetching changes.</p>
<p>The solution is to use a combination of <code>ssh-agent</code> and <code>ssh-add</code>, and it looks
something like this:</p>
<pre><code class="language-bash hljs bash" data-lang="bash"><span class="hljs-meta">#!/bin/bash</span>
ssh-agent `ssh-add <span class="hljs-variable">$OPENSHIFT_DATA_DIR</span>/ssh/github-key &amp;&amp; (
    <span class="hljs-built_in">cd</span> <span class="hljs-variable">$OPENSHIFT_DATA_DIR</span>/config ; 
    git fetch origin ; 
    git rebase origin/mwop.net.config
)`
</code></pre>
<p>After testing the above, I put this in a <code>pre_build</code> script in my OpenShift
configuration so that I can autoupdate my private configuration on each build.
However, I discovered a new problem: when a build is being done, the
<code>ssh-agent</code> is not available, which means the above cannot be executed. I'm
still trying to find a solution.</p>
<h2>Fin</h2>
<p>I'm pretty happy with the move. I don't have to do anything special to automate
deployment, and all my cronjobs and deployment scripts are now self-contained
in the repository, which makes my site more portable. While a few things could
use more documentation, all the pieces are there and discoverable with a small
amount of work.</p>
<p>I'll likely give some other PaaS providers a try in the future, but for the
moment, I'm quite happy with the functionality and flexibility of OpenShift.</p>
<h4>Footnotes</h4>
<ul>
<li><sup id="f1"><a href="#1">1</a></sup> Zend Server's JobQueue can also be used as a
cron replacement, but I was not keen on exposing the job functionality via HTTP.</li>
</ul>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html">OpenShift, Cron, and Naked Domains</a> was originally
    published <time class="dt-published" datetime="2012-12-30T09:52:00-06:00">30 December 2012</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On php-fig and Shared Interfaces</title>
      <pubDate>Thu, 20 Dec 2012 14:23:00 -0600</pubDate>
      <link>https://mwop.net/blog/2012-12-20-on-shared-interfaces.html</link>
      <guid>https://mwop.net/blog/2012-12-20-on-shared-interfaces.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>This is a post I've been meaning to write for a long time, and one requested of
me personally by <a href="http://www.rooftopsolutions.nl/blog/">Evert Pot</a> during the
Dutch PHP Conference in June 2012. It details some observations I have of
php-fig, and hopefully will serve as a record of why I'm not directly
participating any longer.</p>
<p>I was a founding member of the <a href="http://www.php-fig.org/">Framework Interoperability Group</a>,
now called &quot;php-fig&quot;. I was one of around a dozen folks who sat around a table
in 2009 in Chicago during php|tek and started discussions about what we could
all do to make it possible to work better together between our projects, and
make it simpler for users to pick and choose from our projects in order to
build the solutions to their own problems.</p>
<p>The first &quot;standard&quot; that came from this was
<a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md">PSR-0</a>,
which promoted a standard class naming convention that uses a 1:1 relationship
between the namespace and/or vendor prefix and the directory hierarchy, and the
class name and the filename in which it lives. To this day, there are both
those who hail this as a great step forward for cooperation, and simultaneously
others who feel it's a terrible practice.</p>
<p>And then nothing, for years. But a little over a year ago, there was a new push
by a number of folks wanting to do more. Paul Jones did a remarkable job of
spearheading the next
<a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md">two</a>
<a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md">standards</a>,
which centered around coding style. Again, just like with PSR-0, we had both
those feeling it was a huge step forward, and those who loathe the direction.</p>
<p>What was interesting, though, was that once we started seeing some new energy
and momentum, it seemed that <em>everyone</em> wanted a say. And we started getting
dozens of folks a week asking to be voting members, and new proposal after new
proposal. Whether or not somebody likes an existing standard, they want to have
backing for a standard they propose.</p>
<p>And this is when we started seeing proposals surface for shared interfaces,
first around caching, and now around logging (though the latter is the first up
for vote).</p>


<h2>Shared Interfaces</h2>
<p>The idea around shared interfaces is simple: if we can come to a consensus on
the basic interface for a common application task, libraries and frameworks can
typehint on that shared interface, allowing developers to drop in the
implementation of their choosing — or even a standard, reference
implementation. The goal is to prevent Not Invented Here (NIH) syndrome, as
well as to make it simpler to re-use components between one library and
another. As an example, if you're using Framework A, and it has a caching
library, and you're consuming ORM B, you'd be able to pass the same cache
object to the ORM as you use in the framework.</p>
<p>Great goals, really.</p>
<p>But I'm not sure I buy into them.</p>
<h2>Problems</h2>
<p>First, I agree that NIH is a problem.</p>
<p>Second, I <em>also</em> think there's space for <em>multiple implementations</em> of any
given component. Often there are different approaches that different authors
will take: one might focus on performance, another on having multiple adapters
for providing different capabilities, etc. Sometimes having a different
background will present different problem areas you want to resolve. As such,
having multiple implementations can be a very good thing; developers can look
at what each provides, and determine which solves the particular issues
presented in the current project.</p>
<p>Because of this latter point, I have my reservations about shared interfaces.</p>
<p>What if a particular approach requires deviating from the shared interface in
order to accomplish its goals? Additionally, in order to keep the greatest
amount of compatibility between projects, shared interfaces tend to be so
generic that specific implementations require developers to do a ton of manual
type checking and munging of parameters, leading to more overhead, more
difficulty testing and maintaining, and more difficulty documenting and
understanding.</p>
<p>As an example, consider the following (made up) signature for a log method:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">log</span><span class="hljs-params">($message, array $context = null)</span></span>;
</code></pre>
<p>What if your library supports an idea of priorities? Where would that
information go in the above signature — and would that differ between
libraries — would one library use the key for a completely different purpose?
What about logging objects — the signature doesn't say you can't, but how
would I know if a specific implementation supports it, and won't blow up if I
do pass one? Why must the <code>$context</code> be an array — why won't any <code>Traversable</code>
or <code>ArrayAccess</code> object work?</p>
<p>Basically, by being overly generic, the signature becomes a liability for those
implementing the interface; it prevents meaningful interoperability and leads
to splintering implementations.</p>
<p><em>(Please note: the above is completely fictional and has no bearing on current
proposed or accepted standards. It is a thought exercise only.)</em></p>
<p>Furthermore, if a given project writes their own implementation of a component,
and it has specialized features, why would they want to typehint on a generic,
shared interface that doesn't implement those features? This would be
counter-intuitive, as the project would then need to either check on additional
interfaces for the specialized capabilities, duck-type, etc. — all of which
make for more maintenance and code.</p>
<p>In summary, my primary problem with the idea of shared interfaces is that I
feel there is always room for new thinking and ideas in any given problem
space, and that this thinking should not be restricted by what already exists.
Secondarily, I feel that it's okay for a given project to be selective about
what capabilities it requires for its internal consumption and consistency, and
should not limit itself to a standardized interface.</p>
<h2>But, but, SHARING</h2>
<p><em>Remember, the first point I made was that I think NIH is a problem.</em> How do I
reconcile that with a firm stance against shared interfaces?</p>
<p>Easy: <a href="http://en.wikipedia.org/wiki/Bridge_pattern">bridges</a> and/or
<a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapters</a>.</p>
<p>Let's go back to that example of Framework A, its caching library, and working
with ORM B.</p>
<p>Let's assume that ORM B defines an interface for caching, and let's say it
looks like this:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CacheInterface</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">set</span><span class="hljs-params">($key, $data)</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">has</span><span class="hljs-params">($key)</span></span>;
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span><span class="hljs-params">($key)</span></span>;
}
</code></pre>
<p>Furthermore, we'll assume that the expected parameter values and return types
are documented.</p>
<p>What we as a consumer of both Framework A and ORM B can do is build an
<em>implementation</em> of <code>CacheInterface</code> that accepts a cache instance from
Framework A, and proxies the various interface methods to that instance.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FrameworkACache</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CacheInterface</span>
</span>{
    <span class="hljs-keyword">protected</span> $cache;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span><span class="hljs-params">(Cache $cache)</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;cache = $cache;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">set</span><span class="hljs-params">($key, $data)</span>
    </span>{
        $item = <span class="hljs-keyword">new</span> CacheItem($key, $data);
        <span class="hljs-keyword">$this</span>-&gt;cache-&gt;setItem($item);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">has</span><span class="hljs-params">($key)</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;cache-&gt;exists($key);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span><span class="hljs-params">($key)</span>
    </span>{
        $item = <span class="hljs-keyword">$this</span>-&gt;cache-&gt;getItem($key);
        <span class="hljs-keyword">return</span> $item-&gt;getData();
    }
}
</code></pre>
<p>Assuming your code is well-decoupled, and you're using some sort of Inversion
of Control container, you can likely create a factory for your ORM that will
grab the above class, with the cache injected, and inject it into the ORM
instance. Yes, it's a bit more work, but it's difficult to question the end
result: shared caching between the framework and the ORM — and no need for
shared interfaces, nor any need to sacrifice features within the framework or
the ORM.</p>
<h2>Sharing is good, developing solutions is better</h2>
<p>I think the core idea of the php-fig group is sound: <em>let's all start thinking
about how we can make it easier to operate with each other</em>. That said, my
thoughts on how to accomplish that goal have changed significantly, and boil
down to:</p>
<ul>
<li>Use naming conventions that will reduce collisions (i.e., use per-project
vendor prefixes/namespaces)</li>
<li>Use semantic versioning</li>
<li>Keep your installation packages segregated</li>
<li>Have a simple, discoverable way to autoload</li>
<li>Provide interfaces for anything that could benefit from alternate implementations
Don't write code that has side-effects in the global namespace (including
altering PHP settings or superglobals)</li>
</ul>
<p>Following these principals, you can play nice with each other, while still
fostering innovative and differentiating solutions to shared problems.</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-12-20-on-shared-interfaces.html">On php-fig and Shared Interfaces</a> was originally
    published <time class="dt-published" datetime="2012-12-20T14:23:00-06:00">20 December 2012</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>PHP Master Series on Day Camp For Developers</title>
      <pubDate>Tue, 18 Dec 2012 14:24:00 -0600</pubDate>
      <link>https://mwop.net/blog/2012-12-18-php-master-series.html</link>
      <guid>https://mwop.net/blog/2012-12-18-php-master-series.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p><a href="http://blog.calevans.com">Cal Evans</a> has organized another DayCamp4Developers
event, this time entitled <a href="http://blog.calevans.com/2012/11/19/php-master-series-vol-1">&quot;PHP Master Series, Volume 1&quot;</a>.
I'm honored to be an invited speaker for this first edition, where I'll be
presenting my talk, &quot;Designing Beautiful Software&quot;.</p>
<p>Why would you want to participate? Well, for one, because you can interact
directly with the various speakers during the presentations. Sure, you can
likely find the slide decks elsewhere, or possibly even recordings. But if we
all do our jobs right, we'll likely raise more questions than answers; if you
attend, you'll get a chance to ask some of your questions immediately, <em>and we
may even answer them!</em></p>
<p>On top of that, this is a fantastic lineup of speakers, and, frankly, not a
lineup I've ever participated in. In a typical conference, you'd likely see one
or two of us, and be lucky if we weren't scheduled against each other; if you
attend this week, you'll get to see us all, back-to-back.</p>
<p>What else will you be doing this Friday, anyways, while
<a href="http://en.wikipedia.org/wiki/2012_phenomenon">you wait for the end of the world?</a></p>
<p>So, do yourself a favor, and <a href="http://phpmasterseriesv1.eventbrite.com/">register today</a>!</p>




<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-12-18-php-master-series.html">PHP Master Series on Day Camp For Developers</a> was originally
    published <time class="dt-published" datetime="2012-12-18T14:24:00-06:00">18 December 2012</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>My ZendCon Beautiful Software Talk</title>
      <pubDate>Sat, 17 Nov 2012 07:53:00 -0600</pubDate>
      <link>https://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html</link>
      <guid>https://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>Once again, I spoke at <a href="http://www.zendcon.com/">ZendCon</a> this year; in talking
with <a href="http://twitter.com/chwenz">Christian Wenz</a>, we're pretty sure that the
two of us and <a href="http://andigutmans.blogspot.com">Andi</a> are the only ones who
have spoken at all eight events.</p>
<p>Unusually for me, I did not speak on a Zend Framework topic, and had only one
regular slot (I also co-presented a Design Patterns tutorial with my team).
That slot, however, became one of my favorite talks I've delivered: &quot;Designing
Beautiful Software&quot;. I've given this talk a couple times before, but I
completely rewrote it for this conference in order to better convey my core
message: beautiful software is maintainable and extensible; writing software is
a craft.</p>
<p>I discovered today that not only was it recorded, but it's been
<a href="http://youtu.be/mQsQ6QZ4dGg">posted on YouTube</a>:</p>


<p>I've also <a href="//slides.mwop.net/2012-10-25-BeautifulSoftware/BeautifulSoftware.html">posted the slides</a>.</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html">My ZendCon Beautiful Software Talk</a> was originally
    published <time class="dt-published" datetime="2012-11-17T07:53:00-06:00">17 November 2012</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On Visibility in OOP</title>
      <pubDate>Sat, 30 Jun 2012 10:00:00 -0500</pubDate>
      <link>https://mwop.net/blog/2012-06-28-oop-visibility.html</link>
      <guid>https://mwop.net/blog/2012-06-28-oop-visibility.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>I'm a big proponent of object oriented programming. OOP done right helps ease
code maintenance and enables code re-use.</p>
<p>Starting in PHP, OOP enthusiasts got a whole bunch of new tools, and new tools
keep coming into the language for us with each minor release. One feature that
has had a huge impact on frameworks and libraries has been available since the
earliest PHP 5 versions: visibility.</p>


<h2>Theory</h2>
<p>The visibility keywords include <em>private</em>, <em>protected</em>, and <em>public</em>, often
referred to as <strong>PPP</strong>. There's an additional keyword I often lump in with
them, <em>final</em>.</p>
<p>Public visibility is the default, and equivalent to the only visibility
available to PHP prior to version 5: any member declared public is accessible
from any scope. This means the following:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> $bar = <span class="hljs-string">'bar'</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-comment">// I can access within my own scope</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doThat</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// I have access to members in my parent</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar . <span class="hljs-keyword">$this</span>-&gt;baz();
    }
}

$foo = <span class="hljs-keyword">new</span> Foo();

<span class="hljs-comment">// I can access public members from an instance</span>
<span class="hljs-keyword">echo</span> $foo-&gt;bar . $foo-&gt;baz();
</code></pre>
<p>Basically, public visibility means that I can access the member from within the
object, within an extending class, or from simply an instance.</p>
<p>Protected visibility starts to tighten things down a little. With protected
visibility, only the class itself, or an extending class, can access the
member:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $bar = <span class="hljs-string">'bar'</span>;

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-comment">// I can access within my own scope</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doThat</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// I can access protected members in my parent</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar . <span class="hljs-keyword">$this</span>-&gt;baz();
    }
}

$foo = <span class="hljs-keyword">new</span> FooBar();

<span class="hljs-comment">// This works, as I'm calling a public member of an extending class:</span>
$foo-&gt;doThat();

<span class="hljs-comment">// But these are both illegal:</span>
<span class="hljs-keyword">echo</span> $foo-&gt;bar . $foo-&gt;baz();
</code></pre>
<p>Protected visibility is nice for hiding things from those consuming your class.
It can be used to hide implementation details, and to prevent direct
modification of public properties — something important to consider, if a
property may be the product of calculation, or if a particular type is
required.</p>
<p>Private visibility locks things down further. With private visibility, the
object member is only directly modifiable or callable within the declaring
class.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">private</span> $bar = <span class="hljs-string">'bar'</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-comment">// I can access within my own scope</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doThat</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// These are both illegal</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar . <span class="hljs-keyword">$this</span>-&gt;baz();
    }
}

$foo = <span class="hljs-keyword">new</span> FooBar();

<span class="hljs-comment">// These are also both illegal:</span>
<span class="hljs-keyword">echo</span> $foo-&gt;bar . $foo-&gt;baz();
</code></pre>
<p>Private visibility is generally of interest for locking down algorithms. For
instance, if you know that a particular value or operation must not change,
even in extending classes, declaring the member private ensures that extending
classes cannot directly call it.</p>
<p>At any point, you can redeclare a property in an extending class using equal or
more public visibility. The effect of doing so depends on what the visibility
of the member was in the parent class.</p>
<ul>
<li>
<p>In the case of a <em>public</em> property, if an extending class re-declares with
public visibility, any access to the member within the extending class or an
instance of the extending class will see only the new declaration.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> $bar = <span class="hljs-string">'bar'</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> $bar = <span class="hljs-string">'foobar'</span>;
}

$foo = <span class="hljs-keyword">new</span> FooBar();
<span class="hljs-keyword">echo</span> $foo-&gt;bar;   <span class="hljs-comment">// "foobar"</span>
<span class="hljs-keyword">echo</span> $foo-&gt;baz(); <span class="hljs-comment">// "foobar"</span>
</code></pre>
</li>
<li>
<p>In the instance of a <em>protected</em> property, if the extending class re-declares
with either public or protected visibility, you get the same behavior as
public -&gt; public.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $bar = <span class="hljs-string">'bar'</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">public</span> $bar = <span class="hljs-string">'foobar'</span>;
}

$foo = <span class="hljs-keyword">new</span> FooBar();
<span class="hljs-keyword">echo</span> $foo-&gt;bar;   <span class="hljs-comment">// "foobar"</span>
<span class="hljs-keyword">echo</span> $foo-&gt;baz(); <span class="hljs-comment">// "foobar"</span>
</code></pre>
</li>
<li>
<p>In the instance of a <em>private</em> property, things get interesting. The private
value or method will be used for any access made within code declared in the
parent class, but not overridden in the child. However, if the child class
overrides any code, the value of the re-declared instance will be used. This
is far easier to understand via an example.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">private</span> $bar = <span class="hljs-string">'bar'</span>;
    <span class="hljs-keyword">private</span> $baz = <span class="hljs-string">'baz'</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FooBar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $bar = <span class="hljs-string">'foobar'</span>;
    <span class="hljs-keyword">private</span> $baz = <span class="hljs-string">'foobaz'</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBaz</span><span class="hljs-params">()</span> 
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;bar;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBaz2</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;baz;
    }
}

$foo = <span class="hljs-keyword">new</span> FooBar();
<span class="hljs-keyword">echo</span> $foo-&gt;baz();    <span class="hljs-comment">// "bar"</span>
<span class="hljs-keyword">echo</span> $foo-&gt;myBaz();  <span class="hljs-comment">// "foobar"</span>
<span class="hljs-keyword">echo</span> $foo-&gt;myBaz2(); <span class="hljs-comment">// "foobaz"</span>
</code></pre>
</li>
</ul>
<p>My personal takeaway from this is:</p>
<ul>
<li>Use <em>public</em> for members that are safe for anything to call.</li>
<li>Use <em>protected</em> for anything you don't want called from instance methods, not
important to the public API (implementation details), and anything you feel
is safe for extending classes to muck about with.</li>
<li>Use <em>private</em> for any important implementation details that could adversely
affect execution if overridden by an extending class.</li>
</ul>
<p>Those paying attention will note that I skipped <em>final</em>. Actually, I saved that
for last. Marking a class or method <em>final</em> tells PHP that the class or method
may not be extended or re-declared/overridden. At all. I lump this with
visibility, because it's another way of locking down access to an API; marking
something <em>final</em> is saying, &quot;you cannot extend this&quot;, similar to using
<em>private</em>, but without even the possibility of redeclaring.</p>
<h2>Applied</h2>
<p>What got me to thinking about all this was a turn of events with Zend Framework
2. We've had an annotation parser since last summer. <a href="http://ralphschindler.com/">Ralph Schindler</a>
developed it in order to facilitate automatic discovery of injection points for
our Dependency Injection container. Classes could mark a method with the
<code>@Inject</code> annotation, and the various DI compilers would know that that method
needed to be injected.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">use</span> <span class="hljs-title">Zend</span>\<span class="hljs-title">Di</span>\<span class="hljs-title">Definition</span>\<span class="hljs-title">Annotation</span>\<span class="hljs-title">Inject</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $bar;

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@Inject</span>()
     * <span class="hljs-doctag">@param</span>  Bar $bar
     * <span class="hljs-doctag">@return</span> void
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setBar</span><span class="hljs-params">(Bar $bar)</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;bar = $bar;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bar</span> </span>{}
</code></pre>
<p>Recently, part of our Forms RFC included a feature to allow creating forms and
their related input filters by using annotations. Basically, this allows
developers to hint on their domain entities how specific properties should be
filtered, validated, and potentially represented at the form level.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">use</span> <span class="hljs-title">Zend</span>\<span class="hljs-title">Form</span>\<span class="hljs-title">Annotation</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@Annotation</span>\Filter({"name":"StringTrim"})
     * <span class="hljs-doctag">@Annotation</span>\Validator({"name":"Between","options":{"min":5,"max":20}})
     * <span class="hljs-doctag">@Annotation</span>\Attributes({"type":"range"})
     */</span>
    <span class="hljs-keyword">protected</span> $bar;
}
</code></pre>
<p>One developer testing the support wanted to use a combination of
<a href="http://doctrine-project.org">Doctrine</a> annotations and ZF2 form annotations —
that way his entities could also describe validation and representation.</p>
<p>I did some work to make this happen, and everybody was happy. Except then that
same developer went to use that entity with Doctrine, and Doctrine's annotation
parser started raising exceptions on all the ZF2 annotations.</p>
<p>After some debate, I realized: (a) we were basically just making up syntax for
our annotations; it'd be better to use an established syntax; but (b) we should
still retain the ability to use arbitrary syntax, as we can't really know what
sorts of annotations developers may already be using.</p>
<p>So, we decided to make our annotation component depend on the annotations
support in <code>Doctrine\Common</code>, and to use the annotation syntax they utilize. ZF2
would provide some code to make it possible to plug in arbitrary parsers, and
use the <code>Doctrine\Common</code> annotation parser to parse annotations officially
supported by ZF2.</p>
<p>However, when I went to start making this happen, I ran into immediate issues.</p>
<p>Remember how this post is about visibility? Well, the class I was directly
interested in, <code>Doctrine\Common\Annotations\DocParser</code>, not only contains
private members, but is marked <em>final</em>.</p>
<p>My immediate response was to start dissecting the class, cutting and pasting
the bits interesting to my solution into a new class in ZF2. I went down this
route for several hours, gradually pulling in more and more methods as I
discovered how far down the rabbit hole I needed to go to accomplish my task.</p>
<p>But at the back of my head, I kept thinking this was a bad idea. If any patches
ever came in for the original class, I'd need to port them into our ZF2
solution. And I couldn't help but think that I'd miss a crucial piece.</p>
<p>So I started playing with its public API, to see if there were any shortcuts I
might be able to take. And there were.</p>
<p>The class has a public <code>parse()</code> method. Based on how Doctrine uses the code, I
assumed I needed to pass a full PHP docblock in — which ran counter to how I
wanted to use the code. I wanted to pass in an annotation at a time. But when I
looked closer, I realized that the parser didn't require a full docblock; any
fragment would do.</p>
<p>To make a long story short: I was able to feed the parser a single annotation
at a time from ZF2's <code>AnnotationScanner</code>. This allowed me to build a very
simple class that allows registering a set of annotations it can handle, and
feeding it a single annotation string at a time to decide (a) if it supports
it, and (b) to parse it and return the associated annotation object.</p>
<p>In sum: because the class in question was marked final and had private members,
I found myself forced to think critically about what I wanted to accomplish,
and then thoroughly understand the public API to see how I might accomplish
that task without the ability to extend.</p>
<h2>Conclusions</h2>
<p>Doctrine has a policy that encourages
<a href="http://en.wikipedia.org/wiki/Poka-yoke"><em>poka-yoke</em></a> solutions: code should be
executable in a specific way. The policy was developed to both aid users
(having multiple ways of doing something is often confusing), as well as to
ease maintenance (fewer extension points means less liklihood of developers
doing hard-to-debug things in extending code and reporting it back to the
project). These have led them to heavily use <em>private</em> and <em>final</em> visibility.</p>
<p>I've said it before, and I'll say it again: I feel that frameworks and
libraries should use <em>private</em> and <em>final</em> sparingly. Over the years, I've seen
code repurposed in simply wondrous ways — largely due to keeping the code as
open as possible to extension. I like to enable my users as much as possible.</p>
<p>That said, I can also see Doctrine's argument — and can see where, while it can
often be frustrating, it can also lead to potentially more sound and elegant
solutions.</p>
<p>I'll probably continue shying away from <em>private</em> and <em>final</em> visibility, but I
do plan to experiment with it more in the future. What about you?</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-06-28-oop-visibility.html">On Visibility in OOP</a> was originally
    published <time class="dt-published" datetime="2012-06-28T21:20:00-05:00">28 June 2012</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On Error Handling and Closures</title>
      <pubDate>Fri, 16 Dec 2011 11:26:18 -0600</pubDate>
      <link>https://mwop.net/blog/on-error-handling-and-closures.html</link>
      <guid>https://mwop.net/blog/on-error-handling-and-closures.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>The error suppression operator in PHP (<code>@</code>) is often seen as a necessary evil.
Many, many low-level function will return a value indicating an error, but also
raise an <code>E_NOTICE</code> or <code>E_WARNING</code> — things you might be able to recover from,
or conditions where you may want to raise an exception.</p>
<p>So, at times, you find yourself writing code like this:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">false</span> === ($fh = @fopen($filename, <span class="hljs-string">'r'</span>))) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(sprintf(
        <span class="hljs-string">'Could not open file "%s" to read'</span>, $filename
    ));
}
</code></pre>
<p>Seems straight-forward enough, right? But it's wrong on so many levels.</p>


<ul>
<li>The error doesn't magically go away. If you've got PHP's log setup, you're
going to be getting a log entry each time the suppressed statement errors.</li>
<li>Error suppression is expensive. Like, really, really expensive. A special
error handler is registered to prevent the error propagating to the display
(if <code>display_errors</code> is enabled), but errors are still sent to the log (as
noted above). When done, the original error handler has to be restored.</li>
<li>If you use things like <code>error_get_last()</code>, you may find that if you have many
error suppressions, it returns something unrelated to the error that just
occurred.</li>
<li>PHPUnit, anyone? Error suppression and PHPUnit do not play well together. And
there's a reason for that: often suppressed errors are indicative of bigger
issues.</li>
</ul>
<p>So, how do you address it?</p>
<p>PHP has two functions to assist with this: <code>set_error_handler()</code> and
<code>restore_error_handler()</code>. The first takes a callable argument, and optionally
a mask of error levels to which it will respond; the second is used to return
error handling to the previously set handler.</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleError</span><span class="hljs-params">($errno, $errmsg = <span class="hljs-string">''</span>, $errfile = <span class="hljs-string">''</span>, $errline = <span class="hljs-number">0</span>)</span>
</span>{
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(sprintf(
        <span class="hljs-string">'Error reading file (in %s@%d): %s'</span>,
        $errfile, $errline, $errmsg
    ), $errno);
}

set_error_handler(<span class="hljs-string">'handleError'</span>, E_WARNING);
$fh = fopen($filename, <span class="hljs-string">'r'</span>);
restore_error_handler();
</code></pre>
<p>Traditionally, these have been a pain to use, as you have to create individual
functions or methods for handlers, and methods must have public visibility,
even if the functionality is internal to the class.</p>
<p>With PHP 5.3, we get a new option, however: closures.</p>
<p>With closures, error handlers are still a pain to use, but you now get to scope
the handlers directly in the context of the application flow. Let's look at an
example:</p>
<pre><code class="language-php hljs php" data-lang="php">set_error_handler(
    <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">($error, $message = <span class="hljs-string">''</span>, $file = <span class="hljs-string">''</span>, $line = <span class="hljs-number">0</span>)</span> <span class="hljs-title">use</span> <span class="hljs-params">($filename)</span> </span>{
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(sprintf(
            <span class="hljs-string">'Error reading file "%s" (in %s@%d): %s'</span>,
            $filename, $file, $line, $message
        ), $error);
    },
    E_WARNING
);
$fh = fopen($filename, <span class="hljs-string">'r'</span>);
restore_error_handler();
</code></pre>
<p>If you just want to ignore the error, it's even simpler:</p>
<pre><code class="language-php hljs php" data-lang="php">set_error_handler(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>; }, E_NOTICE);
$contents = file_get_contents($filename);
restore_error_handler();
</code></pre>
<p>The code isn't necessarily succinct, which is one reason many gravitate towards
using error suppression instead. However, it has the benefit of being
context-sensitive and robust, which is always a good goal.</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/on-error-handling-and-closures.html">On Error Handling and Closures</a> was originally
    published <time class="dt-published" datetime="2011-12-16T11:26:18-06:00">16 December 2011</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Dependency Injection: An analogy</title>
      <pubDate>Fri, 25 Mar 2011 02:25:13 -0500</pubDate>
      <link>https://mwop.net/blog/260-Dependency-Injection-An-analogy.html</link>
      <guid>https://mwop.net/blog/260-Dependency-Injection-An-analogy.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>I've been working on a proposal for including service locators and dependency
injection containers in Zend Framework 2.0, and one issue I've had is trying to
explain the basic concept to developers unfamiliar with the concepts — or with
pre-conceptions that diverge from the use cases I'm proposing.</p>
<p>In talking with my wife about it a week or two ago, I realized that I needed an
analogy she could understand; I was basically using her as my
<a href="http://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber duck</a>. And it turned
out to be a great idea, as it gave me some good analogies.</p>


<h2>Dining Out</h2>
<p>The analogies go like this: you walk into a burger join, and you're hungry.</p>
<ul>
<li>Dependency Injection is like ordering off the menu — but specifying things
like, &quot;I'd like to substitute portabella mushrooms for the patties, please.&quot;
The waiter then goes and brings your dish, which has portabella mushrooms
instead of the hamburger patties listed on the menu.</li>
<li>Service Location is like ordering with substitutions, and having the waiter
completely ignore the substitutions; you get what's on the menu, nothing more,
nothing less.</li>
</ul>
<p>Now, when it comes to Zend Framework's version 1 releases, we've really got
neither. Our situation is more like a buffet or a kitchen — you grab a little of
this, a little of that, and assemble your own burger. It's a lot more work.</p>
<p>Frankly, I'm lazy, and like my dinner brought to me… and if I want any
substitutions, I'd like those, too.</p>
<h2>Getting the Ingredients</h2>
<p>A number of developers I've talked to seem to think DI is a bit too much &quot;magic&quot;
— they're worried they'll lose control over their application: they won't know
where dependencies are being set.</p>
<p>There are two things to keep in mind:</p>
<ol>
<li>you, the developer, define the dependencies up front</li>
<li>if you don't pull the object from the container, you're in charge</li>
</ol>
<p>Regarding the second point, it appears some developers think that with a DI
container in place, dependencies magically get injected in <em>every</em> object. But
that's simply not the case. If you use normal PHP:</p>
<pre><code class="language-php hljs php" data-lang="php">$o = <span class="hljs-keyword">new</span> SomeClass();
</code></pre>
<p>you'll get a new instance, just like always, configured only with any parameters
you pass in to the constructor or methods you call on it. It's only when you
retrieve the object from the DI container that you dependency injection takes
place; if you do that, you can always examine the DI configuration (which can
either be programmatic or via a configuration file) to determine what
dependencies were configured.</p>
<p>Basically, it's like the difference between making your own hamburger patty out
of fresh ground sirloin, and ordering Animal Style from In-N-Out.</p>
<h2>I'm done now</h2>
<p>What's your favorite way of thinking of these concepts?</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/260-Dependency-Injection-An-analogy.html">Dependency Injection: An analogy</a> was originally
    published <time class="dt-published" datetime="2011-03-21T17:52:15-05:00">21 March 2011</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Aspects, Filters, and Signals, Oh, My!</title>
      <pubDate>Fri, 14 Jan 2011 08:53:52 -0600</pubDate>
      <link>https://mwop.net/blog/251-aspects-filters-and-signals-oh-my.html</link>
      <guid>https://mwop.net/blog/251-aspects-filters-and-signals-oh-my.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>Last month, during <a href="http://phpadvent.org">PHP Advent</a>, <a href="http://ohloh.net/accounts/gwoo">gwoo</a> wrote an interesting post on <a href="http://phpadvent.org/2010/aspect-oriented-design-by-garrett-woodworth">Aspect-Oriented Design</a>, or Aspect Oriented Programming (AOP) as it is more commonly known. The article got me to thinking, and revisiting what I know about AOP, Intercepting Filters, and Signal Slots -- in particular, what use cases I see for them, what the state of current PHP offerings are, and where the future may lie.</p>
<p>But first, some background is probably in order, as this is a jargon-heavy post.</p>


<h2>Aspect Oriented Programming</h2>
<p>I was first introduced to AOP in 2006 via an
<a href="http://www.phparch.com/magazine/2006-2/april/">April 2006 php|architect article by Dmitry Sheiko</a>.
That article detailed adding calls at various places in a method where you might
want to hook into functionality — for instance, to log, cache, etc. Expanding
on this, I considered other possibilities: manipulating incoming arguments,
validation, ACL checks, implementing write-through caching strategies, and more.
The approach is daunting, however; typical, naive implementations lead to a lot
of boiler-plate code:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Listener</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">notify</span><span class="hljs-params">($signal, $argv = null)</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $listeners;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attach</span><span class="hljs-params">($signal, Listener $listener)</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;listeners[$signal][] = $listener;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span><span class="hljs-params">($arg1, $arg2)</span>
    </span>{
        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">$this</span>-&gt;listeners <span class="hljs-keyword">as</span> $listener) {
            $listener-&gt;notify(<span class="hljs-string">'preDoSomething'</span>, func_get_args());
        }
        
        <span class="hljs-comment">// do some work</span>
        
        <span class="hljs-keyword">foreach</span> (<span class="hljs-keyword">$this</span>-&gt;listeners <span class="hljs-keyword">as</span> $listener) {
            $listener-&gt;notify(<span class="hljs-string">'postDoSomething'</span>, $result);
        }
    }
}
</code></pre>
<p>The article didn't go into any real details on how you might short-circuit the
filters or handle return values from them, and aspect handling itself was not
detailed completely. As such, the code begins to add up, particularly if many
classes and/or methods implement the functionality.</p>
<h2>Intercepting Filters</h2>
<p>A similar concept to AOP is the idea of
<a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html">Intercepting</a>
<a href="http://msdn.microsoft.com/en-us/library/ff647251.aspx">Filters</a>. Like AOP, the
idea is to separate cross-cutting concerns such as logging, debugging, and more
from the actual logic the component exposes. The difference is that typically
Intercepting Filters are language independent, have a standard implementation in
a given framework, and can be re-used. The approach gwoo used in his post falls
more under this category.</p>
<p><a href="http://lithify.me/">Lithium</a>, a PHP 5.3 framework and the reference for gwoo's
article, has a very intriguing approach. Instead of calling the filters
explicitly within the body of the code, they suggest that the body of the code
simply becomes one of the filters, via a closure:</p>
<pre><code class="language-php hljs php" data-lang="php">Dispatcher::applyFilter(<span class="hljs-string">'run'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">($self, $params, $chain)</span> </span>{
    <span class="hljs-comment">// do something...</span>
    <span class="hljs-keyword">return</span> $chain-&gt;next($self, $params, $chain);
});
</code></pre>
<p>In Lithium, each filter is responsible for calling the next (each filter
receives the chain as its third and final argument); as soon as one doesn't call
<code>next()</code>, execution is stopped, and the result returned (or at least that's how
I read the source). You can call the chain either before or after the code you
want to execute in each filter; placement will determine whether it's a pre- or
a post-filter. The approach answers a number of the concerns I outlined
previously — namely, standardization of approach, and the ability to
short-circuit execution.</p>
<p>The above example defines a filter that will run when the <code>run()</code> method of the
<code>Dispatcher</code> class is executed. <code>$self</code> will typically be the object instance,
<code>$params</code> an array of the parameters passed to the method, and <code>$chain</code> as
described above. The method itself will execute any filters — typically with
something like this:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">use</span> <span class="hljs-title">lithium</span>/<span class="hljs-title">core</span>/<span class="hljs-title">Object</span> <span class="hljs-title">as</span> <span class="hljs-title">BaseObject</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseObject</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span><span class="hljs-params">($with, $these, $args)</span>
    </span>{
        $params = compact(<span class="hljs-string">'with'</span>, <span class="hljs-string">'these'</span>, <span class="hljs-string">'args'</span>);
        
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;_filter(<span class="hljs-keyword">__METHOD__</span>, $params, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">($self, $params)</span> </span>{
            <span class="hljs-comment">// do the actual work here</span>
            <span class="hljs-keyword">return</span> $result;
        });
    }
}
</code></pre>
<p>(The <code>_filter()</code> method is defined in <code>lithium\core\Object</code>, and basically
passes a local, static chain of filters to Lithium's <code>Filter</code> class for
execution. <code>applyFilter()</code> from the previous example statically adds a callback
under the named method to the chain.)</p>
<p>This solution is elegant — but I see some limitations:</p>
<ul>
<li>
<p>First and foremost, I'm not particularly fond of the filtering functionality
being via static methods on a single class; it introduces a hard-coded, hidden
dependency. This means you cannot provide alternate filtering functionality
without extending the class <em>consuming</em> the filters, nor without either
extending the base filters implementation should you wish to provide a
compatible API (for instance, to introduce an implementation that understands
priorities).</p>
<p>Additionally, the easiest way to implement filtering in Lithium is by
extending the <code>lithium\core\Object</code> class — I could find no examples
elsewhere in the documentation that showed how you would compose the
<code>Filters</code> implementation in your own objects. As such, the easiest way to
compose filters is now via inheritance, which seems to be
counter-productive to the whole rationale behind filtering, to my thinking.</p>
</li>
<li>
<p>Second, the approach of making the body of the calling method a closure makes
it difficult to create non-public helper methods. Inside the filter, you're no
longer in the scope of the object, losing the semantics that tie the various
metadata and functionality of the object together. (The Lithium docs provide
illustrations of how to accomplish this, but they require extra work, and a
keen understanding of how references work in PHP.)</p>
</li>
<li>
<p>Third, it's sometimes useful to have access to the return results of <em>all</em> the
filters (not just the last executed); you may want to aggregate them in some
way, or branch logic based on the various returns.</p>
</li>
<li>
<p>Fourth, it's sometimes useful to have multiple call points within the main
code. As an example, for many caching strategies, you'd check first to see if
you have a cache hit, and return immediatly if found; otherwise, you'd execute
the code, and cache the result prior to returning it. This might be possible
in Lithium with constructs like this:</p>
<pre><code class="language-php hljs php" data-lang="php">Filters::add(<span class="hljs-string">'SomeClass::doSomething'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">($method, $self, $params)</span> </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">null</span> !== ($content = cache_hit($params))) {
        <span class="hljs-keyword">return</span> $content;
    }
    $content = Filters::next($method, $self, $params);
    <span class="hljs-keyword">return</span> $content;
});
</code></pre>
<p>However, if you have several filters such as this, the order then becomes
paramount, and that introduces new complexities.</p>
<p>Another example would be with façade methods, where you may wish to introduce
filters before and after each method call:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomeWorkflow</span><span class="hljs-params">($message)</span>
</span>{
    <span class="hljs-keyword">$this</span>-&gt;somePrivateMethod($message);
    <span class="hljs-keyword">$this</span>-&gt;nextPrivateMethod($message);
    <span class="hljs-keyword">$this</span>-&gt;lastPrivateMethod($message);
}
</code></pre>
<p>(I can already hear <a href="http://nateabele.com/">Nate</a> saying &quot;make those all
filters!&quot; or &quot;filter each method!&quot; — but that's the problem with simple
examples - they can't always express the nuances of a use case.)</p>
</li>
<li>
<p>Fifth, it's useful to be able to attach callbacks that are not aware of the
chain. For instance, you may have code you've already written that works
perfectly fine in a standalone situation — e.g., a logger — and you simply
want to add it to the chain. In the Lithium paradigm, you'd need to
<a href="http://en.wikipedia.org/wiki/Currying">curry</a> the calls in, instead of simply
using the existing method:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-comment">// This:</span>
SomeClass::applyFilter(<span class="hljs-string">'doSomething'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">($self, $params, $chain)</span> <span class="hljs-title">use</span> <span class="hljs-params">($log)</span> </span>{
    $log-&gt;info($params[<span class="hljs-string">'message'</span>];
    $chain-&gt;next($self, $params, $chain);
});
<span class="hljs-comment">// VS:</span>
SomeClass::signals()-&gt;connect(<span class="hljs-string">'doSomething'</span>, $log, <span class="hljs-string">'info'</span>);
</code></pre>
<p>Related to this, I personally dislike aggregating the filter parameters into a
single associative array. I don't like having to test for the existence of
parameters, and would much rather PHP tell me if I'm missing required
parameters or if any fail typehints. That said, doing so provides a consistent
API when filtering.</p>
</li>
</ul>
<p>All in all, however, the approach Lithium provides is very good; it just doesn't
completely suit my tastes or use cases.</p>
<h2>Signal Slots</h2>
<p>Interestingly, the capabilities I need are not far from what Lithium provides —
in fact, I'd argue that the Intercepting Filters of Lithium are actually
probably more akin to another pattern, <a href="http://en.wikipedia.org/wiki/Signals_and_slots">Signal Slots</a>.</p>
<p>With Signal Slots, your code emits <em>signals</em> (Lithium does this — it emits the
name of the method being called); any handler, or <em>slot</em> (<em>filters</em> in Lithium),
connected to the signal is then executed.</p>
<p>As such, you typically have some sort of signal &quot;manager&quot; object (the <code>Filters</code>
class in Lithium) that aggregates signals and attached slots; this manager is
then composed into the object emitting signals. For those of you familiar with
events in JavaScript or other event-driven languages, this should sound quite
familiar.</p>
<p>Such an approach looks like this:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $signals;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signals</span><span class="hljs-params">(SignalSlot $signals = null)</span>
    </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">null</span> === $signals) {
            <span class="hljs-comment">// No argument? make sure we have a signal manager</span>
            <span class="hljs-keyword">if</span> (<span class="hljs-keyword">null</span> === <span class="hljs-keyword">$this</span>-&gt;signals) {
                <span class="hljs-keyword">$this</span>-&gt;signals = <span class="hljs-keyword">new</span> Signals(); <span class="hljs-comment">// SignalSlot implementation</span>
            }
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// Compose in an instance of a signal manager</span>
            <span class="hljs-keyword">$this</span>-&gt;signals = $signals;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;signals;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span><span class="hljs-params">($with, $these, $args)</span>
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;emit(<span class="hljs-string">'doSomething.pre'</span>, <span class="hljs-keyword">$this</span>, $with, $these, $args);
        
        <span class="hljs-comment">// do some work</span>
        <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;emit(<span class="hljs-string">'doSomething.during'</span>, <span class="hljs-keyword">$this</span>, $with, $these, $args);

        <span class="hljs-comment">// do some more work</span>
        <span class="hljs-comment">// This time, pass the result</span>
        <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;emit(<span class="hljs-string">'doSomething.post'</span>, <span class="hljs-keyword">$this</span>, $result, $with, $these, $args);
        <span class="hljs-keyword">return</span> $result;
    }
}

$f = <span class="hljs-keyword">new</span> Foo();
$f-&gt;signals()-&gt;connect(<span class="hljs-string">'doSomething.pre'</span>, $log, <span class="hljs-string">'info'</span>);
$f-&gt;signals()-&gt;connect(<span class="hljs-string">'doSomething.during'</span>, $validator, <span class="hljs-string">'isValid'</span>);
$f-&gt;signals()-&gt;connect(<span class="hljs-string">'doSomething.post'</span>, $indexer, <span class="hljs-string">'index'</span>);
</code></pre>
<p>Basically, a <code>SignalSlot</code> provides an object in which signals and their attached
slots are aggregated. This allows having a single manager for multiple signals
(which is similar to how Lithium's <code>Filters</code> class works), while also providing
a way to emit multiple signals from a single procedure. Additionally, since it
is simply an object, you can compose it in to classes that may emit signals —
without requiring inheritance.</p>
<p>This is the basic approach of the <a href="https://github.com/zendframework/zf2/tree/master/library/Zend/SignalSlot">ZF2 SignalSlot implementation</a>,
as well as that found in <a href="http://components.symfony-project.org/event-dispatcher/">Symfony 2's Event Dispatcher</a>
and <a href="http://incubator.apache.org/zetacomponents/documentation/trunk/SignalSlot/tutorial.html">Zeta Components' SignalSlot component</a>.</p>
<p>Both Symfony 2's Event Dispatcher and ZF2's <code>SignalSlot</code> component build in the
ability to short-circuit, Symfony via a <code>notifyUntil()</code> method, and ZF2 via an
<code>emitUntil</code> method. With ZF2, each time a signal is emitted, a
<code>ResponseCollection</code> is returned by the manager, containing an aggregate of all
slot responses. Calling <code>emitUntil()</code> will short-circuit execution of remaining
slots if a given slot returns a response that validates against given criteria;
at this point, the collection is marked as &quot;stopped&quot;, and you can pull the
&quot;last&quot; response and return it:</p>
<pre><code class="language-php hljs php" data-lang="php">$responses = <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;emitUntil(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">($response)</span> </span>{
    <span class="hljs-keyword">return</span> ($response <span class="hljs-keyword">instanceof</span> SpecificResultType);
}, <span class="hljs-string">'doSomething.pre'</span>, <span class="hljs-keyword">$this</span>, $with, $these, $args);
<span class="hljs-keyword">if</span> ($responses-&gt;stopped()) {
    <span class="hljs-keyword">return</span> $responses-&gt;last();
}
</code></pre>
<p>This introduces extra code in the method emitting the signals — but meets the
criteria that no given slot need be aware of the chain.</p>
<p>The Signal Slot approach actually supports paradigms similar to those
illustrated in Lithium. For instance, I can make my method body a slot:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>
</span>{
    <span class="hljs-keyword">protected</span> $handlers = <span class="hljs-keyword">array</span>();

    <span class="hljs-comment">// ... skip signals composition ...</span>
    
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span><span class="hljs-params">($with, $these, $args)</span>
    </span>{
        $params = compact(<span class="hljs-string">'with'</span>, <span class="hljs-string">'these'</span>, <span class="hljs-string">'args'</span>);
        
        <span class="hljs-comment">// connect() returns a signal handler (slot); store it so that we only</span>
        <span class="hljs-comment">// ever attach it once...</span>
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>(<span class="hljs-keyword">$this</span>-&gt;handlers[<span class="hljs-keyword">__FUNCTION__</span>])) {
            <span class="hljs-keyword">$this</span>-&gt;handlers[<span class="hljs-keyword">__FUNCTION__</span>] = <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;connect(<span class="hljs-keyword">__FUNCTION__</span>, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">($self, $params)</span> </span>{
                <span class="hljs-comment">// do the work here!</span>
            });
        }
        
        <span class="hljs-comment">// Emit the signal, and return the last result</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;signals()-&gt;emit(<span class="hljs-keyword">__FUNCTION__</span>, <span class="hljs-keyword">$this</span>, $params)-&gt;last();
    }
}
</code></pre>
<h2>Concerns</h2>
<p>Using Signal Slots and Intercepting Filters is not without its concerns, nor is
any given implementation perfect.</p>
<ul>
<li>Zeta Components does a fantastic job of handling signal slots. However, you
cannot short-circuit execution, nor introspect return values. It does offer
two features neither ZF2 nor Symfony 2 offer (at this time): the ability to
<em>statically</em> connect slots to signals, allowing you to wire without having an
existing instance, nor even caring what object might emit the signal; and the
ability to add a priority to slots, which allows you to alter the execution
order.</li>
<li>Lithium does a nice job of providing good standards (signals are method names;
parameters are predictable for all handlers), but at the price of some
flexibility (static implementation with no interface for alternate
implementations; no ability to re-use existing methods and functions with
differing signatures without currying).</li>
<li>Symfony 2 offers short-ciruiting and flexibility in callbacks, but requires
that you create an event object to pass to the Event Dispatcher, making the
usage slightly more verbose, and offers no standardization of signal naming.</li>
<li>ZF2's <code>SignalSlots</code> offer similar benefits (and drawbacks) to Symfony 2's
implementation, provides standardization of the signal manager response,
allows registering classes that self-register with the signal handler, but
lacks static wiring capabilities or prioritization.</li>
</ul>
<p>On a more abstract level, signal slots and intercepting filters can lead to
difficulties in learning and mastering code that use them:</p>
<p>How are signals named?</p>
<p>How do you document the parameters available to slots/filters?</p>
<ul>
<li>How can those using IDEs discover available signals? and the arguments expected?</li>
</ul>
<p>Where does the wiring occur?</p>
<ul>
<li>For instance, if any wiring is automated, this can potentially lead to more difficulty in debugging.</li>
<li>If done manually, when, and where?</li>
</ul>
<p>What happens if a slot doesn't receive arguments it needs, or cannot handle the arguments it receives?</p>
<p>In short, while they solve many problems, the implementations also introduce new
concerns — though this will be true of any extension system, in my experience.</p>
<h2>Conclusions</h2>
<p>I personally am a huge fan of Intercepting Filters and Signal Slots. I think
they can make code easier to extend, by providing a standard methodology for
introducing cross-cutting concerns without requiring class extension. They can
also make code quite expressive — sometimes at the cost of readability — by
introducing functional programming paradigms.</p>
<p>If you have not investigated these concepts or components before, I highly
recommend doing so; I think they play a fundamental role in the next generation
of PHP frameworks.</p>
<h2>Caveats</h2>
<p>I am not an expert, nor well-versed, in all the frameworks listed here, and as
such, some of the information may be incorrect or incomplete. I am the author of
ZF2's current Signal Slot implementation, and am still working on improvements
to it.</p>
<h2>Updates</h2>
<ul>
<li><strong>2011-01-10 11:35Z-05:00</strong> Cal Evans found the original php|architect article
I referenced, and I've revised some of the assessments based on re-reading it,
as well as linked to the issue.</li>
</ul>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/251-aspects-filters-and-signals-oh-my.html">Aspects, Filters, and Signals, Oh, My!</a> was originally
    published <time class="dt-published" datetime="2011-01-10T09:30:00-06:00">10 January 2011</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Setting up your Zend_Test test suites</title>
      <pubDate>Sat, 13 Sep 2008 09:37:40 -0500</pubDate>
      <link>https://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html</link>
      <guid>https://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html</guid>
      <author>contact@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>Now that <a href="http://framework.zend.com/manual/en/zend.test.html">Zend_Test</a> has
shipped, developers are of course asking, &quot;How do I setup my test suite?&quot;
Fortunately, after some discussion with my colleagues and a little
experimenting on my one, I can answer that now.</p>


<p><a href="http://phpunit.de">PHPUnit</a> offers a variety of methods for setting up test
suites, some trivial and some complex. The Zend Framework test suite, for
instance, goes for a more complex route, adding component-level suites that
require a fair amount of initial setup, but which allow us fairly fine-grained
control.</p>
<p>However, testing and test automation should be easy and the complex approach is
overkill for most of our applications. Fortunately, PHPUnit offers some other
methods that make doing so relatively simple. The easiest method is to use an
<a href="http://www.phpunit.de/pocket_guide/3.2/en/appendixes.configuration.html">XML configuration file</a>.</p>
<p>As an example, consider the following:</p>
<pre><code class="language-xml hljs xml" data-lang="xml"><span class="hljs-tag">&lt;<span class="hljs-name">phpunit</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">testsuite</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"My Test Suite"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">directory</span>&gt;</span>./<span class="hljs-tag">&lt;/<span class="hljs-name">directory</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">testsuite</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">filter</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">whitelist</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">directory</span> <span class="hljs-attr">suffix</span>=<span class="hljs-string">".php"</span>&gt;</span>../library/<span class="hljs-tag">&lt;/<span class="hljs-name">directory</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">directory</span> <span class="hljs-attr">suffix</span>=<span class="hljs-string">".php"</span>&gt;</span>../application/<span class="hljs-tag">&lt;/<span class="hljs-name">directory</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">exclude</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">directory</span> <span class="hljs-attr">suffix</span>=<span class="hljs-string">".phtml"</span>&gt;</span>../application/<span class="hljs-tag">&lt;/<span class="hljs-name">directory</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">exclude</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">whitelist</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">filter</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">logging</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">log</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"coverage-html"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"./log/report"</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>
            <span class="hljs-attr">yui</span>=<span class="hljs-string">"true"</span> <span class="hljs-attr">highlight</span>=<span class="hljs-string">"true"</span>
            <span class="hljs-attr">lowUpperBound</span>=<span class="hljs-string">"50"</span> <span class="hljs-attr">highLowerBound</span>=<span class="hljs-string">"80"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">log</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"testdox-html"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"./log/testdox.html"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">logging</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">phpunit</span>&gt;</span>
</code></pre>
<p>First thing to note, relative paths are relative to the configuration file.
This allows you to run your tests from anywhere in your tests tree. Second,
providing a <code>directory</code> directive to the <code>testsuite</code> directive scans for all
files ending in <code>Test.php</code> in that directory, meaning you don't have to keep a
list of your test cases manually. It's a great way to automate the suite.
Third, the filter directive allows us to determine what classes to include
and/or exclude from coverage reports. Finally, the <code>logging</code> directive lets us
specify what kinds of logs to create and where.</p>
<p>Drop the above into <code>tests/phpunit.xml</code> in your application, and you can start
writing test cases and running the suite immediately, using the following
command:</p>
<pre><code class="language-bash hljs bash" data-lang="bash">$ phpunit --configuration phpunit.xml
</code></pre>
<p>I like to group my test cases by type. I have controllers, models, and often
library code, and need to keep the tests organized both on the filesystem as
well as for running the actual tests. There are two things I do to facilitate
this.</p>
<p>First, I create directories. For instance, I have the following hierarchy in my
test suite:</p>
<pre><code class="language- hljs " data-lang="">tests/
    phpunit.xml
    TestHelper.php
    controllers/
        IndexControllerTest.php (contains IndexControllerTest)
        ErrorControllerTest.php (contains ErrorControllerTest)
        ...
    models/
        PasteTest.php           (contains PasteTest)
        DbTable/
            PasteTest.php       (contains DbTable_PasteTest)
        ...
    My/
        Form/
            Element/
                SimpleTextareaTest.php
</code></pre>
<p><code>controllers/</code> contains my controllers, <code>models/</code> contains my models. If I were
developing a modular application, I'd have something like <code>blog/controllers/</code>
instead. Library code is given the same hierarchy as is found in my <code>library/</code>
directory.</p>
<p>Second, I use docblock annotations to group my tests. I add the following to my
class-level docblock in my controller test cases:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@group</span> Controllers
 */</span>
</code></pre>
<p>Models get the annotation <code>@group Models</code>, etc. This allows me to run
individual sets of tests on demand:</p>
<pre><code class="language-bash hljs bash" data-lang="bash">$ phpunit --configuration phpunit.xml --group=Controllers
</code></pre>
<p>You can specify multiple <code>@group</code> annotations, which means you can separate
tests into modules, issue report identifiers, etc; additionally, you can add
the annotations to individual test methods themselves to have really
fine-grained test running capabilities.</p>
<p>Astute readers will have noticed the <code>TestHelper.php</code> file in that directory
listing earlier, and will be wondering what that's all about.</p>
<p>A test suite needs some environmental information, just like your application
does. It may need a default database adapter, altered <code>include_path</code>s,
autoloading set up, and more. Here's what my <code>TestHelper.php</code> looks like:</p>
<pre><code class="language-php hljs php" data-lang="php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-comment">/*
 * Start output buffering
 */</span>
ob_start();

<span class="hljs-comment">/*
 * Set error reporting to the level to which code must comply.
 */</span>
error_reporting( E_ALL | E_STRICT );

<span class="hljs-comment">/*
 * Set default timezone
 */</span>
date_default_timezone_set(<span class="hljs-string">'GMT'</span>);

<span class="hljs-comment">/*
 * Testing environment
 */</span>
define(<span class="hljs-string">'APPLICATION_ENV'</span>, <span class="hljs-string">'testing'</span>);

<span class="hljs-comment">/*
 * Determine the root, library, tests, and models directories
 */</span>
$root        = realpath(dirname(<span class="hljs-keyword">__FILE__</span>) . <span class="hljs-string">'/../'</span>);
$library     = $root . <span class="hljs-string">'/library'</span>;
$tests       = $root . <span class="hljs-string">'/tests'</span>;
$models      = $root . <span class="hljs-string">'/application/models'</span>;
$controllers = $root . <span class="hljs-string">'/application/controllers'</span>;

<span class="hljs-comment">/*
 * Prepend the library/, tests/, and models/ directories to the
 * include_path. This allows the tests to run out of the box.
 */</span>
$path = <span class="hljs-keyword">array</span>(
    $models,
    $library,
    $tests,
    get_include_path()
);
set_include_path(implode(PATH_SEPARATOR, $path));

<span class="hljs-comment">/**
 * Register autoloader
 */</span>
<span class="hljs-keyword">require_once</span> <span class="hljs-string">'Zend/Loader.php'</span>;
Zend_Loader::registerAutoload();

<span class="hljs-comment">/**
 * Store application root in registry
 */</span>
Zend_Registry::set(<span class="hljs-string">'testRoot'</span>, $root);
Zend_Registry::set(<span class="hljs-string">'testBootstrap'</span>, $root . <span class="hljs-string">'/application/bootstrap.php'</span>);

<span class="hljs-comment">/*
 * Unset global variables that are no longer needed.
 */</span>
<span class="hljs-keyword">unset</span>($root, $library, $models, $controllers, $tests, $path);
</code></pre>
<p>The above ensures that my <code>APPLICATION_ENV</code> constant is set appropriately, that error reporting is appropriate for tests (i.e., I want to see <em>all</em> errors), and that autoloading is enabled. Additionally, I place a couple items in my registry — the bootstrap and test root directory.</p>
<p>In each test case file, I then do a <code>require_once</code> on this file. In future
versions of PHPUnit, you'll be able to specify a bootstrap file in your
configuration XML that gets pulled in for each test case, and you'll be able to
even further automate your testing environment setup.</p>
<p>Hopefully this will get you started with your application testing; what are you
waiting for?</p>


<div class="h-entry">
    <img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&u=79dd2ea1d4d8855944715d09ee4c86215027fa80&s=140" alt="matthew">
    <a class="u-url u-uid p-name" href="https://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html">Setting up your Zend_Test test suites</a> was originally
    published <time class="dt-published" datetime="2008-09-11T15:00:00-05:00">11 September 2008</time>
    on <a href="https://mwop.net">https://mwop.net</a> by
    <a rel="author" class="p-author" href="https://mwop.net">Matthew Weier O&#039;Phinney</a>.
</div>
]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
  </channel>
</rss>
