<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Blog entries tagged oop :: mwop.net</title>
  <updated>2018-12-05T16:26:00-06:00</updated>
  <generator uri="https://getlaminas.org" version="2">Laminas_Feed_Writer</generator>
  <link rel="alternate" type="text/html" href="https://mwop.net/blog/tag/oop"/>
  <link rel="self" type="application/atom+xml" href="https://mwop.net/blog/tag/oop/atom.xml"/>
  <id>https://mwop.net/blog/tag/oop</id>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Creating Exception types on-the-fly in modern PHP]]></title>
    <published>2018-12-05T16:26:00-06:00</published>
    <updated>2018-12-05T16:26:00-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html"/>
    <id>https://mwop.net/blog/2018-12-05-on-the-fly-exceptions.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml: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:</xhtml:p>
<xhtml:ul>
<xhtml:li>We would create a marker <xhtml:code>ExceptionInterface</xhtml:code> for
each package.</xhtml:li>
<xhtml:li>We would extend <xhtml:a href="http://php.net/manual/en/spl.exceptions.php">SPL exceptions</xhtml:a>
and implement the package marker interface when doing so.</xhtml:li>
</xhtml:ul>
<xhtml:p>What this gave users was the ability to catch in three ways:</xhtml:p>
<xhtml:ul>
<xhtml:li>They could catch the most specific exception type by class
name.</xhtml:li>
<xhtml:li>They could catch all package-level exceptions using the marker
interface.</xhtml:li>
<xhtml:li>The could catch general exceptions using the associated SPL
type.</xhtml:li>
</xhtml:ul>
<xhtml:p>So, as an example:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">try</xhtml:span> {
    $do-&gt;something();
} <xhtml:span class="hljs-keyword">catch</xhtml:span> (MostSpecificException $e) {
} <xhtml:span class="hljs-keyword">catch</xhtml:span> (PackageLevelExceptionInterface $e) {
} <xhtml:span class="hljs-keyword">catch</xhtml:span> (\RuntimeException $e) {
}
</xhtml:code></xhtml:pre>
<xhtml:p>This kind of granularity is really nice to work with. So nice
that some standards produced by <xhtml:a href="https://www.php-fig.org/">PHP-FIG</xhtml:a> now ship them, such as
<xhtml:a href="https://www.php-fig.org/psr/psr-11/">PSR-11</xhtml:a>, which
ships a <xhtml:code>ContainerExceptionInterface</xhtml:code> and a
<xhtml:code>NotFoundExceptionInterface</xhtml:code>.</xhtml:p>
<xhtml:blockquote>
<xhtml:p>One thing we've started doing recently as we make packages
support only PHP 7 versions is to have the marker
<xhtml:code>ExceptionInterface</xhtml:code> extend the <xhtml:code>Throwable</xhtml:code>
interface; this ensures that implementations <xhtml:strong>must</xhtml:strong>
be able to be thrown!</xhtml:p>
</xhtml:blockquote>
<xhtml: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?</xhtml:p>
<xhtml:p>Why, use an anonymous class, of course!</xhtml:p>
<xhtml:p>As an example, I was writing up some documentation that
illustrated a custom <xhtml:code>ContainerInterface</xhtml:code> implementation
today, and realized I needed to throw an exception at one point,
specifically a
<xhtml:code>Psr\Container\NotFoundExceptionInterface</xhtml:code>. I wrote up
the following snippet:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">$message = sprintf(<xhtml:span class="hljs-comment">/* ... */</xhtml:span>);
<xhtml:span class="hljs-keyword">throw</xhtml:span> <xhtml:span class="hljs-keyword">new</xhtml:span> <xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span>($<xhtml:span class="hljs-title">message</xhtml:span>) <xhtml:span class="hljs-keyword">extends</xhtml:span> <xhtml:span class="hljs-title">RuntimeException</xhtml:span> <xhtml:span class="hljs-keyword">implements</xhtml:span>
    <xhtml:span class="hljs-title">NotFoundExceptionInterface</xhtml:span> </xhtml:span>{
};
</xhtml:code></xhtml:pre>
<xhtml:p>Done!</xhtml:p>
<xhtml:p>This works because <xhtml:code>RuntimeException</xhtml:code> takes a message
as the first constructor argument; by extending that class, I gain
that behavior. Since <xhtml:code>NotFoundExceptionInterface</xhtml:code> is a
marker interface, I did not need to add any additional behavior, so
this inline example works out-of-the-box.</xhtml:p>
<xhtml:p>What else are <xhtml:em>you</xhtml:em> using anonymous classes for?</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally
published <xhtml:time class="dt-published" datetime="2018-12-05T16:26:00-06:00">5 December 2018</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[OpenShift, Cron, and Naked Domains]]></title>
    <published>2012-12-30T09:52:00-06:00</published>
    <updated>2012-12-30T09:52:00-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html"/>
    <id>https://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>As an experiment, I migrated my website over to <xhtml:a href="http://openshift.redhat.com">OpenShift</xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>Cron</xhtml:h2>
<xhtml:p>OpenShift offers a <xhtml:a href="http://en.wikipedia.org/wiki/Cron">Cron</xhtml:a> cartridge, which I was
excited to try out.<xhtml:sup id="ref-1"><xhtml:a href="#f1">1</xhtml:a></xhtml:sup></xhtml:p>
<xhtml:p>The basics are quite easy. In your repository's
<xhtml:code>.openshift</xhtml:code> directory is a <xhtml:code>cron</xhtml:code>
subdirectory, further divided into <xhtml:code>minutely</xhtml:code>,
<xhtml:code>hourly</xhtml:code>, <xhtml:code>daily</xhtml:code>, <xhtml:code>weekly</xhtml:code>, and
<xhtml:code>monthly</xhtml:code> subdirectories. You drop a script you want to
run into one of these directories, and push your changes
upstream.</xhtml:p>
<xhtml: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?</xhtml:p>
<xhtml: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
<xhtml:code>hourly</xhtml:code> directory so that it can test more
frequently:</xhtml:p>
<xhtml:pre><xhtml:code class="language-bash hljs bash" data-lang="bash"><xhtml:span class="hljs-meta">#!/bin/bash</xhtml:span>
<xhtml:span class="hljs-keyword">if</xhtml:span> [ `date +%H` == <xhtml:span class="hljs-string">"05"</xhtml:span> ]
<xhtml:span class="hljs-keyword">then</xhtml:span>
    (
        <xhtml:span class="hljs-built_in">export</xhtml:span> PHP=/usr/<xhtml:span class="hljs-built_in">local</xhtml:span>/zend/bin/php ;
        <xhtml:span class="hljs-built_in">cd</xhtml:span> <xhtml:span class="hljs-variable">$OPENSHIFT_REPO_DIR</xhtml:span> ; 
        <xhtml:span class="hljs-variable">$PHP</xhtml:span> public/index.php phlycomic fetch all ; 
        <xhtml:span class="hljs-variable">$PHP</xhtml:span> public/index.php phlysimplepage cache clear --page=pages/comics 
    )
<xhtml:span class="hljs-keyword">fi</xhtml:span>
</xhtml:code></xhtml:pre>
<xhtml:p>And here's one that runs on the quarter-hour, placed in the
<xhtml:code>minutely</xhtml:code> directory:</xhtml:p>
<xhtml:pre><xhtml:code class="language-bash hljs bash" data-lang="bash"><xhtml:span class="hljs-meta">#!/bin/bash</xhtml:span>
MINUTES=`date +%M`

<xhtml:span class="hljs-keyword">for</xhtml:span> i <xhtml:span class="hljs-keyword">in</xhtml:span> <xhtml:span class="hljs-string">"00"</xhtml:span> <xhtml:span class="hljs-string">"15"</xhtml:span> <xhtml:span class="hljs-string">"30"</xhtml:span> <xhtml:span class="hljs-string">"45"</xhtml:span>;<xhtml:span class="hljs-keyword">do</xhtml:span>
    <xhtml:span class="hljs-keyword">if</xhtml:span> [ <xhtml:span class="hljs-string">"<xhtml:span class="hljs-variable">$MINUTES</xhtml:span>"</xhtml:span> == <xhtml:span class="hljs-string">"<xhtml:span class="hljs-variable">$i</xhtml:span>"</xhtml:span> ];<xhtml:span class="hljs-keyword">then</xhtml:span>
        (
            <xhtml:span class="hljs-built_in">export</xhtml:span> PHP=/usr/<xhtml:span class="hljs-built_in">local</xhtml:span>/zend/bin/php ;
            <xhtml:span class="hljs-built_in">cd</xhtml:span> <xhtml:span class="hljs-variable">$OPENSHIFT_REPO_DIR</xhtml:span> ;
            <xhtml:span class="hljs-variable">$PHP</xhtml:span> public/index.php githubfeed fetch 
        )
    <xhtml:span class="hljs-keyword">fi</xhtml:span>
<xhtml:span class="hljs-keyword">done</xhtml:span>
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:h2>Naked Domains</xhtml:h2>
<xhtml:p>Naked domains are domains without a preceding subdomain. In my
case, this means "mwop.net", vs. "www.mwop.net".</xhtml:p>
<xhtml: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 "virtual" domain registered with your cloud
hosting provider.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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: <xhtml:a href="http://wwwizer.com/naked-domain-redirect">wwwizer</xhtml:a>. You simply
point your naked domain A record to the wwwizer IP address, and
they will do a redirect to your <xhtml:code>www</xhtml:code> subdomain.</xhtml:p>
<xhtml:p>I implemented wwwizer on my domain (which is why you'll see
"www.mwop.net" in your location bar), and it's been working
flawlessly since doing so.</xhtml:p>
<xhtml:h4>Private repositories</xhtml:h4>
<xhtml: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
<xhtml:a href="https://help.github.com/articles/managing-deploy-keys">GitHub
deploy keys</xhtml:a> on my server in order to retrieve changes.</xhtml:p>
<xhtml:p>This was simple enough: I created an <xhtml:code>ssh</xhtml:code>
subdirectory in my <xhtml:code>$OPENSHIFT_DATA_DIR</xhtml:code> directory, and
generated a new SSH keypair.</xhtml:p>
<xhtml:p>The problem was telling SSH to <xhtml:em>use</xhtml:em> this key when
fetching changes.</xhtml:p>
<xhtml:p>The solution is to use a combination of <xhtml:code>ssh-agent</xhtml:code>
and <xhtml:code>ssh-add</xhtml:code>, and it looks something like this:</xhtml:p>
<xhtml:pre><xhtml:code class="language-bash hljs bash" data-lang="bash"><xhtml:span class="hljs-meta">#!/bin/bash</xhtml:span>
ssh-agent `ssh-add <xhtml:span class="hljs-variable">$OPENSHIFT_DATA_DIR</xhtml:span>/ssh/github-key &amp;&amp; (
    <xhtml:span class="hljs-built_in">cd</xhtml:span> <xhtml:span class="hljs-variable">$OPENSHIFT_DATA_DIR</xhtml:span>/config ; 
    git fetch origin ; 
    git rebase origin/mwop.net.config
)`
</xhtml:code></xhtml:pre>
<xhtml:p>After testing the above, I put this in a <xhtml:code>pre_build</xhtml: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 <xhtml:code>ssh-agent</xhtml:code> is
not available, which means the above cannot be executed. I'm still
trying to find a solution.</xhtml:p>
<xhtml:h2>Fin</xhtml:h2>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h4>Footnotes</xhtml:h4>
<xhtml:ul>
<xhtml:li><xhtml:sup id="f1"><xhtml:a href="#1">1</xhtml:a></xhtml: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.</xhtml:li>
</xhtml:ul>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2012-12-30T09:52:00-06:00">30
December 2012</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[On php-fig and Shared Interfaces]]></title>
    <published>2012-12-20T14:23:00-06:00</published>
    <updated>2012-12-20T14:23:00-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2012-12-20-on-shared-interfaces.html"/>
    <id>https://mwop.net/blog/2012-12-20-on-shared-interfaces.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>This is a post I've been meaning to write for a long time, and
one requested of me personally by <xhtml:a href="http://www.rooftopsolutions.nl/blog/">Evert Pot</xhtml: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.</xhtml:p>
<xhtml:p>I was a founding member of the <xhtml:a href="http://www.php-fig.org/">Framework Interoperability Group</xhtml:a>, now
called "php-fig". 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.</xhtml:p>
<xhtml:p>The first "standard" that came from this was <xhtml:a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md">
PSR-0</xhtml: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.</xhtml:p>
<xhtml: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 <xhtml:a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md">
two</xhtml:a> <xhtml:a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md">
standards</xhtml: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.</xhtml:p>
<xhtml:p>What was interesting, though, was that once we started seeing
some new energy and momentum, it seemed that <xhtml:em>everyone</xhtml: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.</xhtml:p>
<xhtml: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).</xhtml:p>
<xhtml:h2>Shared Interfaces</xhtml:h2>
<xhtml: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.</xhtml:p>
<xhtml:p>Great goals, really.</xhtml:p>
<xhtml:p>But I'm not sure I buy into them.</xhtml:p>
<xhtml:h2>Problems</xhtml:h2>
<xhtml:p>First, I agree that NIH is a problem.</xhtml:p>
<xhtml:p>Second, I <xhtml:em>also</xhtml:em> think there's space for <xhtml:em>multiple
implementations</xhtml: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.</xhtml:p>
<xhtml:p>Because of this latter point, I have my reservations about
shared interfaces.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p>As an example, consider the following (made up) signature for a
log method:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">log</xhtml:span><xhtml:span class="hljs-params">($message, array $context = null)</xhtml:span></xhtml:span>;
</xhtml:code></xhtml:pre>
<xhtml: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 <xhtml:code>$context</xhtml:code> be an array — why won't any
<xhtml:code>Traversable</xhtml:code> or <xhtml:code>ArrayAccess</xhtml:code> object
work?</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p><xhtml:em>(Please note: the above is completely fictional and has no
bearing on current proposed or accepted standards. It is a thought
exercise only.)</xhtml:em></xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>But, but, SHARING</xhtml:h2>
<xhtml:p><xhtml:em>Remember, the first point I made was that I think NIH is a
problem.</xhtml:em> How do I reconcile that with a firm stance against
shared interfaces?</xhtml:p>
<xhtml:p>Easy: <xhtml:a href="http://en.wikipedia.org/wiki/Bridge_pattern">bridges</xhtml:a> and/or
<xhtml:a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapters</xhtml:a>.</xhtml:p>
<xhtml:p>Let's go back to that example of Framework A, its caching
library, and working with ORM B.</xhtml:p>
<xhtml:p>Let's assume that ORM B defines an interface for caching, and
let's say it looks like this:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">interface</xhtml:span> <xhtml:span class="hljs-title">CacheInterface</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">set</xhtml:span><xhtml:span class="hljs-params">($key, $data)</xhtml:span></xhtml:span>;
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">has</xhtml:span><xhtml:span class="hljs-params">($key)</xhtml:span></xhtml:span>;
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">get</xhtml:span><xhtml:span class="hljs-params">($key)</xhtml:span></xhtml:span>;
}
</xhtml:code></xhtml:pre>
<xhtml:p>Furthermore, we'll assume that the expected parameter values and
return types are documented.</xhtml:p>
<xhtml:p>What we as a consumer of both Framework A and ORM B can do is
build an <xhtml:em>implementation</xhtml:em> of <xhtml:code>CacheInterface</xhtml:code>
that accepts a cache instance from Framework A, and proxies the
various interface methods to that instance.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">FrameworkACache</xhtml:span> <xhtml:span class="hljs-keyword">implements</xhtml:span> <xhtml:span class="hljs-title">CacheInterface</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">protected</xhtml:span> $cache;

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

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

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

    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">get</xhtml:span><xhtml:span class="hljs-params">($key)</xhtml:span>
    </xhtml:span>{
        $item = <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;cache-&gt;getItem($key);
        <xhtml:span class="hljs-keyword">return</xhtml:span> $item-&gt;getData();
    }
}
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:h2>Sharing is good, developing solutions is better</xhtml:h2>
<xhtml:p>I think the core idea of the php-fig group is sound: <xhtml:em>let's
all start thinking about how we can make it easier to operate with
each other</xhtml:em>. That said, my thoughts on how to accomplish that
goal have changed significantly, and boil down to:</xhtml:p>
<xhtml:ul>
<xhtml:li>Use naming conventions that will reduce collisions (i.e., use
per-project vendor prefixes/namespaces)</xhtml:li>
<xhtml:li>Use semantic versioning</xhtml:li>
<xhtml:li>Keep your installation packages segregated</xhtml:li>
<xhtml:li>Have a simple, discoverable way to autoload</xhtml:li>
<xhtml: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)</xhtml:li>
</xhtml:ul>
<xhtml:p>Following these principals, you can play nice with each other,
while still fostering innovative and differentiating solutions to
shared problems.</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2012-12-20T14:23:00-06:00">20
December 2012</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[PHP Master Series on Day Camp For Developers]]></title>
    <published>2012-12-18T14:24:00-06:00</published>
    <updated>2012-12-18T14:24:00-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2012-12-18-php-master-series.html"/>
    <id>https://mwop.net/blog/2012-12-18-php-master-series.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p><xhtml:a href="http://blog.calevans.com">Cal Evans</xhtml:a> has organized
another DayCamp4Developers event, this time entitled <xhtml:a href="http://blog.calevans.com/2012/11/19/php-master-series-vol-1">"PHP
Master Series, Volume 1"</xhtml:a>. I'm honored to be an invited speaker
for this first edition, where I'll be presenting my talk,
"Designing Beautiful Software".</xhtml:p>
<xhtml: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, <xhtml:em>and we may
even answer them!</xhtml:em></xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p>What else will you be doing this Friday, anyways, while <xhtml:a href="http://en.wikipedia.org/wiki/2012_phenomenon">you wait for the end
of the world?</xhtml:a></xhtml:p>
<xhtml:p>So, do yourself a favor, and <xhtml:a href="http://phpmasterseriesv1.eventbrite.com/">register today</xhtml:a>!</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally
published <xhtml:time class="dt-published" datetime="2012-12-18T14:24:00-06:00">18 December 2012</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[My ZendCon Beautiful Software Talk]]></title>
    <published>2012-11-17T07:53:00-06:00</published>
    <updated>2012-11-17T07:53:00-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html"/>
    <id>https://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Once again, I spoke at <xhtml:a href="http://www.zendcon.com/">ZendCon</xhtml:a> this year; in talking with
<xhtml:a href="http://twitter.com/chwenz">Christian Wenz</xhtml:a>, we're
pretty sure that the two of us and <xhtml:a href="http://andigutmans.blogspot.com">Andi</xhtml:a> are the only ones who
have spoken at all eight events.</xhtml:p>
<xhtml: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: "Designing Beautiful Software". 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.</xhtml:p>
<xhtml:p>I discovered today that not only was it recorded, but it's been
<xhtml:a href="http://youtu.be/mQsQ6QZ4dGg">posted on YouTube</xhtml:a>:</xhtml:p>
<xhtml:p>I've also <xhtml:a href="//slides.mwop.net/2012-10-25-BeautifulSoftware/BeautifulSoftware.html">
posted the slides</xhtml:a>.</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2012-11-17T07:53:00-06:00">17
November 2012</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[On Visibility in OOP]]></title>
    <published>2012-06-28T21:20:00-05:00</published>
    <updated>2012-06-30T10:00:00-05:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/2012-06-28-oop-visibility.html"/>
    <id>https://mwop.net/blog/2012-06-28-oop-visibility.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>I'm a big proponent of object oriented programming. OOP done
right helps ease code maintenance and enables code re-use.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>Theory</xhtml:h2>
<xhtml:p>The visibility keywords include <xhtml:em>private</xhtml:em>,
<xhtml:em>protected</xhtml:em>, and <xhtml:em>public</xhtml:em>, often referred to as
<xhtml:strong>PPP</xhtml:strong>. There's an additional keyword I often lump in
with them, <xhtml:em>final</xhtml:em>.</xhtml:p>
<xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">public</xhtml:span> $bar = <xhtml:span class="hljs-string">'bar'</xhtml:span>;

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

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

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

<xhtml:span class="hljs-comment">// I can access public members from an instance</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;bar . $foo-&gt;baz();
</xhtml:code></xhtml:pre>
<xhtml:p>Basically, public visibility means that I can access the member
from within the object, within an extending class, or from simply
an instance.</xhtml:p>
<xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">protected</xhtml:span> $bar = <xhtml:span class="hljs-string">'bar'</xhtml:span>;

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

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

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

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

<xhtml:span class="hljs-comment">// But these are both illegal:</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;bar . $foo-&gt;baz();
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:p>Private visibility locks things down further. With private
visibility, the object member is only directly modifiable or
callable within the declaring class.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">private</xhtml:span> $bar = <xhtml:span class="hljs-string">'bar'</xhtml:span>;

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

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

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

<xhtml:span class="hljs-comment">// These are also both illegal:</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;bar . $foo-&gt;baz();
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml:p>In the case of a <xhtml:em>public</xhtml: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.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">public</xhtml:span> $bar = <xhtml:span class="hljs-string">'bar'</xhtml:span>;

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

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

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

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

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

$foo = <xhtml:span class="hljs-keyword">new</xhtml:span> FooBar();
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;bar;   <xhtml:span class="hljs-comment">// "foobar"</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;baz(); <xhtml:span class="hljs-comment">// "foobar"</xhtml:span>
</xhtml:code></xhtml:pre></xhtml:li>
<xhtml:li>
<xhtml:p>In the instance of a <xhtml:em>private</xhtml: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.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">private</xhtml:span> $bar = <xhtml:span class="hljs-string">'bar'</xhtml:span>;
    <xhtml:span class="hljs-keyword">private</xhtml:span> $baz = <xhtml:span class="hljs-string">'baz'</xhtml:span>;

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

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

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

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

$foo = <xhtml:span class="hljs-keyword">new</xhtml:span> FooBar();
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;baz();    <xhtml:span class="hljs-comment">// "bar"</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;myBaz();  <xhtml:span class="hljs-comment">// "foobar"</xhtml:span>
<xhtml:span class="hljs-keyword">echo</xhtml:span> $foo-&gt;myBaz2(); <xhtml:span class="hljs-comment">// "foobaz"</xhtml:span>
</xhtml:code></xhtml:pre></xhtml:li>
</xhtml:ul>
<xhtml:p>My personal takeaway from this is:</xhtml:p>
<xhtml:ul>
<xhtml:li>Use <xhtml:em>public</xhtml:em> for members that are safe for anything to
call.</xhtml:li>
<xhtml:li>Use <xhtml:em>protected</xhtml: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.</xhtml:li>
<xhtml:li>Use <xhtml:em>private</xhtml:em> for any important implementation details
that could adversely affect execution if overridden by an extending
class.</xhtml:li>
</xhtml:ul>
<xhtml:p>Those paying attention will note that I skipped <xhtml:em>final</xhtml:em>.
Actually, I saved that for last. Marking a class or method
<xhtml:em>final</xhtml: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 <xhtml:em>final</xhtml:em> is saying, "you cannot extend
this", similar to using <xhtml:em>private</xhtml:em>, but without even the
possibility of redeclaring.</xhtml:p>
<xhtml:h2>Applied</xhtml:h2>
<xhtml: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.
<xhtml:a href="http://ralphschindler.com/">Ralph Schindler</xhtml:a> developed
it in order to facilitate automatic discovery of injection points
for our Dependency Injection container. Classes could mark a method
with the <xhtml:code>@Inject</xhtml:code> annotation, and the various DI
compilers would know that that method needed to be injected.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">use</xhtml:span> <xhtml:span class="hljs-title">Zend</xhtml:span>\<xhtml:span class="hljs-title">Di</xhtml:span>\<xhtml:span class="hljs-title">Definition</xhtml:span>\<xhtml:span class="hljs-title">Annotation</xhtml:span>\<xhtml:span class="hljs-title">Inject</xhtml:span>;

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

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

<xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Bar</xhtml:span> </xhtml:span>{}
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">use</xhtml:span> <xhtml:span class="hljs-title">Zend</xhtml:span>\<xhtml:span class="hljs-title">Form</xhtml:span>\<xhtml:span class="hljs-title">Annotation</xhtml:span>;

<xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-comment">/**
     * <xhtml:span class="hljs-doctag">@Annotation</xhtml:span>\Filter({"name":"StringTrim"})
     * <xhtml:span class="hljs-doctag">@Annotation</xhtml:span>\Validator({"name":"Between","options":{"min":5,"max":20}})
     * <xhtml:span class="hljs-doctag">@Annotation</xhtml:span>\Attributes({"type":"range"})
     */</xhtml:span>
    <xhtml:span class="hljs-keyword">protected</xhtml:span> $bar;
}
</xhtml:code></xhtml:pre>
<xhtml:p>One developer testing the support wanted to use a combination of
<xhtml:a href="http://doctrine-project.org">Doctrine</xhtml:a> annotations and
ZF2 form annotations — that way his entities could also describe
validation and representation.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p>So, we decided to make our annotation component depend on the
annotations support in <xhtml:code>Doctrine\Common</xhtml: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
<xhtml:code>Doctrine\Common</xhtml:code> annotation parser to parse annotations
officially supported by ZF2.</xhtml:p>
<xhtml:p>However, when I went to start making this happen, I ran into
immediate issues.</xhtml:p>
<xhtml:p>Remember how this post is about visibility? Well, the class I
was directly interested in,
<xhtml:code>Doctrine\Common\Annotations\DocParser</xhtml:code>, not only
contains private members, but is marked <xhtml:em>final</xhtml:em>.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p>The class has a public <xhtml:code>parse()</xhtml: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.</xhtml:p>
<xhtml:p>To make a long story short: I was able to feed the parser a
single annotation at a time from ZF2's
<xhtml:code>AnnotationScanner</xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>Conclusions</xhtml:h2>
<xhtml:p>Doctrine has a policy that encourages <xhtml:a href="http://en.wikipedia.org/wiki/Poka-yoke"><xhtml:em>poka-yoke</xhtml:em></xhtml: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 <xhtml:em>private</xhtml:em> and
<xhtml:em>final</xhtml:em> visibility.</xhtml:p>
<xhtml:p>I've said it before, and I'll say it again: I feel that
frameworks and libraries should use <xhtml:em>private</xhtml:em> and
<xhtml:em>final</xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:p>I'll probably continue shying away from <xhtml:em>private</xhtml:em> and
<xhtml:em>final</xhtml:em> visibility, but I do plan to experiment with it more
in the future. What about you?</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml:a class="u-url u-uid p-name" href="https://mwop.net/blog/2012-06-28-oop-visibility.html">On
Visibility in OOP</xhtml:a> was originally published <xhtml:time class="dt-published" datetime="2012-06-28T21:20:00-05:00">28 June
2012</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by
<xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew
Weier O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[On Error Handling and Closures]]></title>
    <published>2011-12-16T11:26:18-06:00</published>
    <updated>2011-12-16T11:26:18-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/on-error-handling-and-closures.html"/>
    <id>https://mwop.net/blog/on-error-handling-and-closures.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>The error suppression operator in PHP (<xhtml:code>@</xhtml:code>) is often
seen as a necessary evil. Many, many low-level function will return
a value indicating an error, but also raise an
<xhtml:code>E_NOTICE</xhtml:code> or <xhtml:code>E_WARNING</xhtml:code> — things you might
be able to recover from, or conditions where you may want to raise
an exception.</xhtml:p>
<xhtml:p>So, at times, you find yourself writing code like this:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">if</xhtml:span> (<xhtml:span class="hljs-keyword">false</xhtml:span> === ($fh = @fopen($filename, <xhtml:span class="hljs-string">'r'</xhtml:span>))) {
    <xhtml:span class="hljs-keyword">throw</xhtml:span> <xhtml:span class="hljs-keyword">new</xhtml:span> RuntimeException(sprintf(
        <xhtml:span class="hljs-string">'Could not open file "%s" to read'</xhtml:span>, $filename
    ));
}
</xhtml:code></xhtml:pre>
<xhtml:p>Seems straight-forward enough, right? But it's wrong on so many
levels.</xhtml:p>
<xhtml:ul>
<xhtml: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.</xhtml:li>
<xhtml:li>Error suppression is expensive. Like, really, really expensive.
A special error handler is registered to prevent the error
propagating to the display (if <xhtml:code>display_errors</xhtml:code> is
enabled), but errors are still sent to the log (as noted above).
When done, the original error handler has to be restored.</xhtml:li>
<xhtml:li>If you use things like <xhtml:code>error_get_last()</xhtml:code>, you may
find that if you have many error suppressions, it returns something
unrelated to the error that just occurred.</xhtml:li>
<xhtml: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.</xhtml:li>
</xhtml:ul>
<xhtml:p>So, how do you address it?</xhtml:p>
<xhtml:p>PHP has two functions to assist with this:
<xhtml:code>set_error_handler()</xhtml:code> and
<xhtml:code>restore_error_handler()</xhtml: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.</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">handleError</xhtml:span><xhtml:span class="hljs-params">($errno, $errmsg = <xhtml:span class="hljs-string">''</xhtml:span>, $errfile = <xhtml:span class="hljs-string">''</xhtml:span>, $errline = <xhtml:span class="hljs-number">0</xhtml:span>)</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">throw</xhtml:span> <xhtml:span class="hljs-keyword">new</xhtml:span> RuntimeException(sprintf(
        <xhtml:span class="hljs-string">'Error reading file (in %s@%d): %s'</xhtml:span>,
        $errfile, $errline, $errmsg
    ), $errno);
}

set_error_handler(<xhtml:span class="hljs-string">'handleError'</xhtml:span>, E_WARNING);
$fh = fopen($filename, <xhtml:span class="hljs-string">'r'</xhtml:span>);
restore_error_handler();
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:p>With PHP 5.3, we get a new option, however: closures.</xhtml:p>
<xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">set_error_handler(
    <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span><xhtml:span class="hljs-params">($error, $message = <xhtml:span class="hljs-string">''</xhtml:span>, $file = <xhtml:span class="hljs-string">''</xhtml:span>, $line = <xhtml:span class="hljs-number">0</xhtml:span>)</xhtml:span> <xhtml:span class="hljs-title">use</xhtml:span> <xhtml:span class="hljs-params">($filename)</xhtml:span> </xhtml:span>{
        <xhtml:span class="hljs-keyword">throw</xhtml:span> <xhtml:span class="hljs-keyword">new</xhtml:span> RuntimeException(sprintf(
            <xhtml:span class="hljs-string">'Error reading file "%s" (in %s@%d): %s'</xhtml:span>,
            $filename, $file, $line, $message
        ), $error);
    },
    E_WARNING
);
$fh = fopen($filename, <xhtml:span class="hljs-string">'r'</xhtml:span>);
restore_error_handler();
</xhtml:code></xhtml:pre>
<xhtml:p>If you just want to ignore the error, it's even simpler:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">set_error_handler(<xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span><xhtml:span class="hljs-params">()</xhtml:span> </xhtml:span>{ <xhtml:span class="hljs-keyword">return</xhtml:span> <xhtml:span class="hljs-keyword">true</xhtml:span>; }, E_NOTICE);
$contents = file_get_contents($filename);
restore_error_handler();
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml:a class="u-url u-uid p-name" href="https://mwop.net/blog/on-error-handling-and-closures.html">On
Error Handling and Closures</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2011-12-16T11:26:18-06:00">16
December 2011</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Dependency Injection: An analogy]]></title>
    <published>2011-03-21T17:52:15-05:00</published>
    <updated>2011-03-25T02:25:13-05:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/260-Dependency-Injection-An-analogy.html"/>
    <id>https://mwop.net/blog/260-Dependency-Injection-An-analogy.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml: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.</xhtml:p>
<xhtml: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 <xhtml:a href="http://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber
duck</xhtml:a>. And it turned out to be a great idea, as it gave me some
good analogies.</xhtml:p>
<xhtml:h2>Dining Out</xhtml:h2>
<xhtml:p>The analogies go like this: you walk into a burger join, and
you're hungry.</xhtml:p>
<xhtml:ul>
<xhtml:li>Dependency Injection is like ordering off the menu — but
specifying things like, "I'd like to substitute portabella
mushrooms for the patties, please." The waiter then goes and brings
your dish, which has portabella mushrooms instead of the hamburger
patties listed on the menu.</xhtml:li>
<xhtml: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.</xhtml:li>
</xhtml:ul>
<xhtml: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.</xhtml:p>
<xhtml:p>Frankly, I'm lazy, and like my dinner brought to me… and if I
want any substitutions, I'd like those, too.</xhtml:p>
<xhtml:h2>Getting the Ingredients</xhtml:h2>
<xhtml:p>A number of developers I've talked to seem to think DI is a bit
too much "magic" — they're worried they'll lose control over their
application: they won't know where dependencies are being set.</xhtml:p>
<xhtml:p>There are two things to keep in mind:</xhtml:p>
<xhtml:ol>
<xhtml:li>you, the developer, define the dependencies up front</xhtml:li>
<xhtml:li>if you don't pull the object from the container, you're in
charge</xhtml:li>
</xhtml:ol>
<xhtml:p>Regarding the second point, it appears some developers think
that with a DI container in place, dependencies magically get
injected in <xhtml:em>every</xhtml:em> object. But that's simply not the case.
If you use normal PHP:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">$o = <xhtml:span class="hljs-keyword">new</xhtml:span> SomeClass();
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>I'm done now</xhtml:h2>
<xhtml:p>What's your favorite way of thinking of these concepts?</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml:a class="u-url u-uid p-name" href="https://mwop.net/blog/260-Dependency-Injection-An-analogy.html">Dependency
Injection: An analogy</xhtml:a> was originally published <xhtml:time class="dt-published" datetime="2011-03-21T17:52:15-05:00">21 March
2011</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by
<xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew
Weier O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Aspects, Filters, and Signals, Oh, My!]]></title>
    <published>2011-01-10T09:30:00-06:00</published>
    <updated>2011-01-14T08:53:52-06:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/251-aspects-filters-and-signals-oh-my.html"/>
    <id>https://mwop.net/blog/251-aspects-filters-and-signals-oh-my.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Last month, during <xhtml:a href="http://phpadvent.org">PHP
Advent</xhtml:a>, <xhtml:a href="http://ohloh.net/accounts/gwoo">gwoo</xhtml:a> wrote
an interesting post on <xhtml:a href="http://phpadvent.org/2010/aspect-oriented-design-by-garrett-woodworth">
Aspect-Oriented Design</xhtml: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.</xhtml:p>
<xhtml:p>But first, some background is probably in order, as this is a
jargon-heavy post.</xhtml:p>
<xhtml:h2>Aspect Oriented Programming</xhtml:h2>
<xhtml:p>I was first introduced to AOP in 2006 via an <xhtml:a href="http://www.phparch.com/magazine/2006-2/april/">April 2006
php|architect article by Dmitry Sheiko</xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">interface</xhtml:span> <xhtml:span class="hljs-title">Listener</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">notify</xhtml:span><xhtml:span class="hljs-params">($signal, $argv = null)</xhtml:span></xhtml:span>;
}

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

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

    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">doSomething</xhtml:span><xhtml:span class="hljs-params">($arg1, $arg2)</xhtml:span>
    </xhtml:span>{
        <xhtml:span class="hljs-keyword">foreach</xhtml:span> (<xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;listeners <xhtml:span class="hljs-keyword">as</xhtml:span> $listener) {
            $listener-&gt;notify(<xhtml:span class="hljs-string">'preDoSomething'</xhtml:span>, func_get_args());
        }
        
        <xhtml:span class="hljs-comment">// do some work</xhtml:span>
        
        <xhtml:span class="hljs-keyword">foreach</xhtml:span> (<xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;listeners <xhtml:span class="hljs-keyword">as</xhtml:span> $listener) {
            $listener-&gt;notify(<xhtml:span class="hljs-string">'postDoSomething'</xhtml:span>, $result);
        }
    }
}
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:h2>Intercepting Filters</xhtml:h2>
<xhtml:p>A similar concept to AOP is the idea of <xhtml:a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html">
Intercepting</xhtml:a> <xhtml:a href="http://msdn.microsoft.com/en-us/library/ff647251.aspx">Filters</xhtml: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.</xhtml:p>
<xhtml:p><xhtml:a href="http://lithify.me/">Lithium</xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">Dispatcher::applyFilter(<xhtml:span class="hljs-string">'run'</xhtml:span>, <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-params">($self, $params, $chain)</xhtml:span> </xhtml:span>{
    <xhtml:span class="hljs-comment">// do something...</xhtml:span>
    <xhtml:span class="hljs-keyword">return</xhtml:span> $chain-&gt;next($self, $params, $chain);
});
</xhtml:code></xhtml:pre>
<xhtml: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 <xhtml:code>next()</xhtml: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.</xhtml:p>
<xhtml:p>The above example defines a filter that will run when the
<xhtml:code>run()</xhtml:code> method of the <xhtml:code>Dispatcher</xhtml:code> class is
executed. <xhtml:code>$self</xhtml:code> will typically be the object instance,
<xhtml:code>$params</xhtml:code> an array of the parameters passed to the
method, and <xhtml:code>$chain</xhtml:code> as described above. The method
itself will execute any filters — typically with something like
this:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">use</xhtml:span> <xhtml:span class="hljs-title">lithium</xhtml:span>/<xhtml:span class="hljs-title">core</xhtml:span>/<xhtml:span class="hljs-title">Object</xhtml:span> <xhtml:span class="hljs-title">as</xhtml:span> <xhtml:span class="hljs-title">BaseObject</xhtml:span>;

<xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span> <xhtml:span class="hljs-keyword">extends</xhtml:span> <xhtml:span class="hljs-title">BaseObject</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">doSomething</xhtml:span><xhtml:span class="hljs-params">($with, $these, $args)</xhtml:span>
    </xhtml:span>{
        $params = compact(<xhtml:span class="hljs-string">'with'</xhtml:span>, <xhtml:span class="hljs-string">'these'</xhtml:span>, <xhtml:span class="hljs-string">'args'</xhtml:span>);
        
        <xhtml:span class="hljs-keyword">return</xhtml:span> <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;_filter(<xhtml:span class="hljs-keyword">__METHOD__</xhtml:span>, $params, <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-params">($self, $params)</xhtml:span> </xhtml:span>{
            <xhtml:span class="hljs-comment">// do the actual work here</xhtml:span>
            <xhtml:span class="hljs-keyword">return</xhtml:span> $result;
        });
    }
}
</xhtml:code></xhtml:pre>
<xhtml:p>(The <xhtml:code>_filter()</xhtml:code> method is defined in
<xhtml:code>lithium\core\Object</xhtml:code>, and basically passes a local,
static chain of filters to Lithium's <xhtml:code>Filter</xhtml:code> class for
execution. <xhtml:code>applyFilter()</xhtml:code> from the previous example
statically adds a callback under the named method to the
chain.)</xhtml:p>
<xhtml:p>This solution is elegant — but I see some limitations:</xhtml:p>
<xhtml:ul>
<xhtml:li>
<xhtml: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 <xhtml:em>consuming</xhtml: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).</xhtml:p>
<xhtml:p>Additionally, the easiest way to implement filtering in Lithium
is by extending the <xhtml:code>lithium\core\Object</xhtml:code> class — I
could find no examples elsewhere in the documentation that showed
how you would compose the <xhtml:code>Filters</xhtml: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.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml: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.)</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml:p>Third, it's sometimes useful to have access to the return
results of <xhtml:em>all</xhtml: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.</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml: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:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">Filters::add(<xhtml:span class="hljs-string">'SomeClass::doSomething'</xhtml:span>, <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-params">($method, $self, $params)</xhtml:span> </xhtml:span>{
    <xhtml:span class="hljs-keyword">if</xhtml:span> (<xhtml:span class="hljs-keyword">null</xhtml:span> !== ($content = cache_hit($params))) {
        <xhtml:span class="hljs-keyword">return</xhtml:span> $content;
    }
    $content = Filters::next($method, $self, $params);
    <xhtml:span class="hljs-keyword">return</xhtml:span> $content;
});
</xhtml:code></xhtml:pre>
<xhtml:p>However, if you have several filters such as this, the order
then becomes paramount, and that introduces new complexities.</xhtml:p>
<xhtml:p>Another example would be with façade methods, where you may wish
to introduce filters before and after each method call:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">doSomeWorkflow</xhtml:span><xhtml:span class="hljs-params">($message)</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;somePrivateMethod($message);
    <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;nextPrivateMethod($message);
    <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;lastPrivateMethod($message);
}
</xhtml:code></xhtml:pre>
<xhtml:p>(I can already hear <xhtml:a href="http://nateabele.com/">Nate</xhtml:a>
saying "make those all filters!" or "filter each method!" — but
that's the problem with simple examples - they can't always express
the nuances of a use case.)</xhtml:p>
</xhtml:li>
<xhtml:li>
<xhtml: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 <xhtml:a href="http://en.wikipedia.org/wiki/Currying">curry</xhtml:a> the calls in,
instead of simply using the existing method:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-comment">// This:</xhtml:span>
SomeClass::applyFilter(<xhtml:span class="hljs-string">'doSomething'</xhtml:span>, <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-params">($self, $params, $chain)</xhtml:span> <xhtml:span class="hljs-title">use</xhtml:span> <xhtml:span class="hljs-params">($log)</xhtml:span> </xhtml:span>{
    $log-&gt;info($params[<xhtml:span class="hljs-string">'message'</xhtml:span>];
    $chain-&gt;next($self, $params, $chain);
});
<xhtml:span class="hljs-comment">// VS:</xhtml:span>
SomeClass::signals()-&gt;connect(<xhtml:span class="hljs-string">'doSomething'</xhtml:span>, $log, <xhtml:span class="hljs-string">'info'</xhtml:span>);
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
</xhtml:li>
</xhtml:ul>
<xhtml:p>All in all, however, the approach Lithium provides is very good;
it just doesn't completely suit my tastes or use cases.</xhtml:p>
<xhtml:h2>Signal Slots</xhtml:h2>
<xhtml: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,
<xhtml:a href="http://en.wikipedia.org/wiki/Signals_and_slots">Signal
Slots</xhtml:a>.</xhtml:p>
<xhtml:p>With Signal Slots, your code emits <xhtml:em>signals</xhtml:em> (Lithium
does this — it emits the name of the method being called); any
handler, or <xhtml:em>slot</xhtml:em> (<xhtml:em>filters</xhtml:em> in Lithium), connected
to the signal is then executed.</xhtml:p>
<xhtml:p>As such, you typically have some sort of signal "manager" object
(the <xhtml:code>Filters</xhtml: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.</xhtml:p>
<xhtml:p>Such an approach looks like this:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">protected</xhtml:span> $signals;

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

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

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

$f = <xhtml:span class="hljs-keyword">new</xhtml:span> Foo();
$f-&gt;signals()-&gt;connect(<xhtml:span class="hljs-string">'doSomething.pre'</xhtml:span>, $log, <xhtml:span class="hljs-string">'info'</xhtml:span>);
$f-&gt;signals()-&gt;connect(<xhtml:span class="hljs-string">'doSomething.during'</xhtml:span>, $validator, <xhtml:span class="hljs-string">'isValid'</xhtml:span>);
$f-&gt;signals()-&gt;connect(<xhtml:span class="hljs-string">'doSomething.post'</xhtml:span>, $indexer, <xhtml:span class="hljs-string">'index'</xhtml:span>);
</xhtml:code></xhtml:pre>
<xhtml:p>Basically, a <xhtml:code>SignalSlot</xhtml: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 <xhtml:code>Filters</xhtml: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.</xhtml:p>
<xhtml:p>This is the basic approach of the <xhtml:a href="https://github.com/zendframework/zf2/tree/master/library/Zend/SignalSlot">
ZF2 SignalSlot implementation</xhtml:a>, as well as that found in
<xhtml:a href="http://components.symfony-project.org/event-dispatcher/">Symfony
2's Event Dispatcher</xhtml:a> and <xhtml:a href="http://incubator.apache.org/zetacomponents/documentation/trunk/SignalSlot/tutorial.html">
Zeta Components' SignalSlot component</xhtml:a>.</xhtml:p>
<xhtml:p>Both Symfony 2's Event Dispatcher and ZF2's
<xhtml:code>SignalSlot</xhtml:code> component build in the ability to
short-circuit, Symfony via a <xhtml:code>notifyUntil()</xhtml:code> method, and
ZF2 via an <xhtml:code>emitUntil</xhtml:code> method. With ZF2, each time a
signal is emitted, a <xhtml:code>ResponseCollection</xhtml:code> is returned by
the manager, containing an aggregate of all slot responses. Calling
<xhtml:code>emitUntil()</xhtml: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
"stopped", and you can pull the "last" response and return it:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php">$responses = <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;signals()-&gt;emitUntil(<xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span><xhtml:span class="hljs-params">($response)</xhtml:span> </xhtml:span>{
    <xhtml:span class="hljs-keyword">return</xhtml:span> ($response <xhtml:span class="hljs-keyword">instanceof</xhtml:span> SpecificResultType);
}, <xhtml:span class="hljs-string">'doSomething.pre'</xhtml:span>, <xhtml:span class="hljs-keyword">$this</xhtml:span>, $with, $these, $args);
<xhtml:span class="hljs-keyword">if</xhtml:span> ($responses-&gt;stopped()) {
    <xhtml:span class="hljs-keyword">return</xhtml:span> $responses-&gt;last();
}
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:p>The Signal Slot approach actually supports paradigms similar to
those illustrated in Lithium. For instance, I can make my method
body a slot:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-class"><xhtml:span class="hljs-keyword">class</xhtml:span> <xhtml:span class="hljs-title">Foo</xhtml:span>
</xhtml:span>{
    <xhtml:span class="hljs-keyword">protected</xhtml:span> $handlers = <xhtml:span class="hljs-keyword">array</xhtml:span>();

    <xhtml:span class="hljs-comment">// ... skip signals composition ...</xhtml:span>
    
    <xhtml:span class="hljs-keyword">public</xhtml:span> <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span> <xhtml:span class="hljs-title">doSomething</xhtml:span><xhtml:span class="hljs-params">($with, $these, $args)</xhtml:span>
    </xhtml:span>{
        $params = compact(<xhtml:span class="hljs-string">'with'</xhtml:span>, <xhtml:span class="hljs-string">'these'</xhtml:span>, <xhtml:span class="hljs-string">'args'</xhtml:span>);
        
        <xhtml:span class="hljs-comment">// connect() returns a signal handler (slot); store it so that we only</xhtml:span>
        <xhtml:span class="hljs-comment">// ever attach it once...</xhtml:span>
        <xhtml:span class="hljs-keyword">if</xhtml:span> (<xhtml:span class="hljs-keyword">isset</xhtml:span>(<xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;handlers[<xhtml:span class="hljs-keyword">__FUNCTION__</xhtml:span>])) {
            <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;handlers[<xhtml:span class="hljs-keyword">__FUNCTION__</xhtml:span>] = <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;signals()-&gt;connect(<xhtml:span class="hljs-keyword">__FUNCTION__</xhtml:span>, <xhtml:span class="hljs-function"><xhtml:span class="hljs-keyword">function</xhtml:span><xhtml:span class="hljs-params">($self, $params)</xhtml:span> </xhtml:span>{
                <xhtml:span class="hljs-comment">// do the work here!</xhtml:span>
            });
        }
        
        <xhtml:span class="hljs-comment">// Emit the signal, and return the last result</xhtml:span>
        <xhtml:span class="hljs-keyword">return</xhtml:span> <xhtml:span class="hljs-keyword">$this</xhtml:span>-&gt;signals()-&gt;emit(<xhtml:span class="hljs-keyword">__FUNCTION__</xhtml:span>, <xhtml:span class="hljs-keyword">$this</xhtml:span>, $params)-&gt;last();
    }
}
</xhtml:code></xhtml:pre>
<xhtml:h2>Concerns</xhtml:h2>
<xhtml:p>Using Signal Slots and Intercepting Filters is not without its
concerns, nor is any given implementation perfect.</xhtml:p>
<xhtml:ul>
<xhtml: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 <xhtml:em>statically</xhtml: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.</xhtml:li>
<xhtml: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).</xhtml:li>
<xhtml: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.</xhtml:li>
<xhtml:li>ZF2's <xhtml:code>SignalSlots</xhtml: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.</xhtml:li>
</xhtml:ul>
<xhtml:p>On a more abstract level, signal slots and intercepting filters
can lead to difficulties in learning and mastering code that use
them:</xhtml:p>
<xhtml:p>How are signals named?</xhtml:p>
<xhtml:p>How do you document the parameters available to
slots/filters?</xhtml:p>
<xhtml:ul>
<xhtml:li>How can those using IDEs discover available signals? and the
arguments expected?</xhtml:li>
</xhtml:ul>
<xhtml:p>Where does the wiring occur?</xhtml:p>
<xhtml:ul>
<xhtml:li>For instance, if any wiring is automated, this can potentially
lead to more difficulty in debugging.</xhtml:li>
<xhtml:li>If done manually, when, and where?</xhtml:li>
</xhtml:ul>
<xhtml:p>What happens if a slot doesn't receive arguments it needs, or
cannot handle the arguments it receives?</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>Conclusions</xhtml:h2>
<xhtml: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.</xhtml:p>
<xhtml: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.</xhtml:p>
<xhtml:h2>Caveats</xhtml:h2>
<xhtml: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.</xhtml:p>
<xhtml:h2>Updates</xhtml:h2>
<xhtml:ul>
<xhtml:li><xhtml:strong>2011-01-10 11:35Z-05:00</xhtml: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.</xhtml:li>
</xhtml:ul>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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!</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2011-01-10T09:30:00-06:00">10
January 2011</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
  <entry xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <title type="html"><![CDATA[Setting up your Zend_Test test suites]]></title>
    <published>2008-09-11T15:00:00-05:00</published>
    <updated>2008-09-13T09:37:40-05:00</updated>
    <link rel="alternate" type="text/html" href="https://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html"/>
    <id>https://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html</id>
    <author>
      <name>Matthew Weier O'Phinney</name>
      <email>contact@mwop.net</email>
      <uri>https://mwop.net</uri>
    </author>
    <content xmlns:xhtml="http://www.w3.org/1999/xhtml" type="xhtml">
      <xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml"><xhtml:p>Now that <xhtml:a href="http://framework.zend.com/manual/en/zend.test.html">Zend_Test</xhtml:a>
has shipped, developers are of course asking, "How do I setup my
test suite?" Fortunately, after some discussion with my colleagues
and a little experimenting on my one, I can answer that now.</xhtml:p>
<xhtml:p><xhtml:a href="http://phpunit.de">PHPUnit</xhtml: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.</xhtml:p>
<xhtml: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 <xhtml:a href="http://www.phpunit.de/pocket_guide/3.2/en/appendixes.configuration.html">
XML configuration file</xhtml:a>.</xhtml:p>
<xhtml:p>As an example, consider the following:</xhtml:p>
<xhtml:pre><xhtml:code class="language-xml hljs xml" data-lang="xml"><xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">phpunit</xhtml:span>&gt;</xhtml:span>
    <xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">testsuite</xhtml:span> <xhtml:span class="hljs-attr">name</xhtml:span>=<xhtml:span class="hljs-string">"My Test Suite"</xhtml:span>&gt;</xhtml:span>
        <xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">directory</xhtml:span>&gt;</xhtml:span>./<xhtml:span class="hljs-tag">&lt;/<xhtml:span class="hljs-name">directory</xhtml:span>&gt;</xhtml:span>
    <xhtml:span class="hljs-tag">&lt;/<xhtml:span class="hljs-name">testsuite</xhtml:span>&gt;</xhtml:span>

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

    <xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">logging</xhtml:span>&gt;</xhtml:span>
        <xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">log</xhtml:span> <xhtml:span class="hljs-attr">type</xhtml:span>=<xhtml:span class="hljs-string">"coverage-html"</xhtml:span> <xhtml:span class="hljs-attr">target</xhtml:span>=<xhtml:span class="hljs-string">"./log/report"</xhtml:span> <xhtml:span class="hljs-attr">charset</xhtml:span>=<xhtml:span class="hljs-string">"UTF-8"</xhtml:span>
            <xhtml:span class="hljs-attr">yui</xhtml:span>=<xhtml:span class="hljs-string">"true"</xhtml:span> <xhtml:span class="hljs-attr">highlight</xhtml:span>=<xhtml:span class="hljs-string">"true"</xhtml:span>
            <xhtml:span class="hljs-attr">lowUpperBound</xhtml:span>=<xhtml:span class="hljs-string">"50"</xhtml:span> <xhtml:span class="hljs-attr">highLowerBound</xhtml:span>=<xhtml:span class="hljs-string">"80"</xhtml:span>/&gt;</xhtml:span>
        <xhtml:span class="hljs-tag">&lt;<xhtml:span class="hljs-name">log</xhtml:span> <xhtml:span class="hljs-attr">type</xhtml:span>=<xhtml:span class="hljs-string">"testdox-html"</xhtml:span> <xhtml:span class="hljs-attr">target</xhtml:span>=<xhtml:span class="hljs-string">"./log/testdox.html"</xhtml:span> /&gt;</xhtml:span>
    <xhtml:span class="hljs-tag">&lt;/<xhtml:span class="hljs-name">logging</xhtml:span>&gt;</xhtml:span>
<xhtml:span class="hljs-tag">&lt;/<xhtml:span class="hljs-name">phpunit</xhtml:span>&gt;</xhtml:span>
</xhtml:code></xhtml:pre>
<xhtml: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 <xhtml:code>directory</xhtml:code>
directive to the <xhtml:code>testsuite</xhtml:code> directive scans for all
files ending in <xhtml:code>Test.php</xhtml: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 <xhtml:code>logging</xhtml:code> directive lets
us specify what kinds of logs to create and where.</xhtml:p>
<xhtml:p>Drop the above into <xhtml:code>tests/phpunit.xml</xhtml:code> in your
application, and you can start writing test cases and running the
suite immediately, using the following command:</xhtml:p>
<xhtml:pre><xhtml:code class="language-bash hljs bash" data-lang="bash">$ phpunit --configuration phpunit.xml
</xhtml:code></xhtml:pre>
<xhtml: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.</xhtml:p>
<xhtml:p>First, I create directories. For instance, I have the following
hierarchy in my test suite:</xhtml:p>
<xhtml:pre><xhtml: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
</xhtml:code></xhtml:pre>
<xhtml:p><xhtml:code>controllers/</xhtml:code> contains my controllers,
<xhtml:code>models/</xhtml:code> contains my models. If I were developing a
modular application, I'd have something like
<xhtml:code>blog/controllers/</xhtml:code> instead. Library code is given the
same hierarchy as is found in my <xhtml:code>library/</xhtml:code>
directory.</xhtml:p>
<xhtml:p>Second, I use docblock annotations to group my tests. I add the
following to my class-level docblock in my controller test
cases:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-comment">/**
 * <xhtml:span class="hljs-doctag">@group</xhtml:span> Controllers
 */</xhtml:span>
</xhtml:code></xhtml:pre>
<xhtml:p>Models get the annotation <xhtml:code>@group Models</xhtml:code>, etc. This
allows me to run individual sets of tests on demand:</xhtml:p>
<xhtml:pre><xhtml:code class="language-bash hljs bash" data-lang="bash">$ phpunit --configuration phpunit.xml --group=Controllers
</xhtml:code></xhtml:pre>
<xhtml:p>You can specify multiple <xhtml:code>@group</xhtml: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.</xhtml:p>
<xhtml:p>Astute readers will have noticed the <xhtml:code>TestHelper.php</xhtml:code>
file in that directory listing earlier, and will be wondering what
that's all about.</xhtml:p>
<xhtml:p>A test suite needs some environmental information, just like
your application does. It may need a default database adapter,
altered <xhtml:code>include_path</xhtml:code>s, autoloading set up, and more.
Here's what my <xhtml:code>TestHelper.php</xhtml:code> looks like:</xhtml:p>
<xhtml:pre><xhtml:code class="language-php hljs php" data-lang="php"><xhtml:span class="hljs-meta">&lt;?php</xhtml:span>
<xhtml:span class="hljs-comment">/*
 * Start output buffering
 */</xhtml:span>
ob_start();

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

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

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

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

<xhtml: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.
 */</xhtml:span>
$path = <xhtml:span class="hljs-keyword">array</xhtml:span>(
    $models,
    $library,
    $tests,
    get_include_path()
);
set_include_path(implode(PATH_SEPARATOR, $path));

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

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

<xhtml:span class="hljs-comment">/*
 * Unset global variables that are no longer needed.
 */</xhtml:span>
<xhtml:span class="hljs-keyword">unset</xhtml:span>($root, $library, $models, $controllers, $tests, $path);
</xhtml:code></xhtml:pre>
<xhtml:p>The above ensures that my <xhtml:code>APPLICATION_ENV</xhtml:code> constant
is set appropriately, that error reporting is appropriate for tests
(i.e., I want to see <xhtml:em>all</xhtml:em> errors), and that autoloading is
enabled. Additionally, I place a couple items in my registry — the
bootstrap and test root directory.</xhtml:p>
<xhtml:p>In each test case file, I then do a <xhtml:code>require_once</xhtml: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.</xhtml:p>
<xhtml:p>Hopefully this will get you started with your application
testing; what are you waiting for?</xhtml:p>
<xhtml:div class="h-entry"><xhtml:img class="u-photo photo" width="50" src="https://avatars0.githubusercontent.com/u/25943?v=3&amp;u=79dd2ea1d4d8855944715d09ee4c86215027fa80&amp;s=140" alt="matthew"/> <xhtml: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</xhtml:a> was originally published
<xhtml:time class="dt-published" datetime="2008-09-11T15:00:00-05:00">11
September 2008</xhtml:time> on <xhtml:a href="https://mwop.net">https://mwop.net</xhtml:a> by <xhtml:a rel="author" class="p-author" href="https://mwop.net">Matthew Weier
O'Phinney</xhtml:a>.</xhtml:div>
</xhtml:div>
    </content>
  </entry>
</feed>
