<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
  <channel>
    <title>Tag: oop :: phly, boy, phly</title>
    <description>Tag: oop :: phly, boy, phly</description>
    <pubDate>Sun, 30 Dec 2012 15:52:00 +0000</pubDate>
    <generator>Zend_Feed_Writer 2.1.4dev (http://framework.zend.com)</generator>
    <link>http://mwop.net/blog/tag/oop.html</link>
    <atom:link rel="self" type="application/rss+xml" href="http://mwop.net/blog/tag/oop-rss.xml"/>
    <item>
      <title>OpenShift, Cron, and Naked Domains</title>
      <pubDate>Sun, 30 Dec 2012 15:52:00 +0000</pubDate>
      <link>http://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html</link>
      <guid>http://mwop.net/blog/2012-12-30-openshift-cron-and-naked-domains.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    As an experiment, I migrated my website over to <a 
    href="http://openshift.redhat.com">OpenShift</a> yesterday. I've been hosting
    a pastebin there already, and have found the service to be both straightforward
    and flexible; it was time to put it to a more thorough test.
</p>

<p>
    In the process, I ran into a number of interesting issues, some of which took quite
    some time to resolve; this post is both to help inform other potential users of the
    service, as well as act as a reminder to myself.
</p><h2>Cron</h2>

<p>
    OpenShift offers a <a href="http://en.wikipedia.org/wiki/Cron">Cron</a> cartridge,
    which I was excited to try out.<sup><a href="#f1">1</a></sup>
</p>

<p>
    The basics are quite easy. In your repository's <code>.openshift</code> 
    directory is a <code>cron</code> subdirectory, further divided into 
    <code>minutely</code>, <code>hourly</code>, <code>daily</code>, <code>weekly</code>,
    and <code>monthly</code> subdirectories. You drop a script you want to run
    into one of these directories, and push your changes upstream.
</p>

<p>
    The problem is: what if I want a job to run at a specific time daily? or on 
    the quarter hour? or on a specific day of the week?
</p>

<p>
    As it turns out, you can manage all of the above, just not quite as succinctly as
    you would in a normal crontab. Here, for example, is a script that I run at 
    5AM daily; I placed it in the <code>hourly</code> directory so that it can test
    more frequently:
</p>

<div class="example"><pre><code language="bash">
#!/bin/bash
if [ `date +%H` == "05" ]
then
    (
        export PHP=/usr/local/zend/bin/php ;
        cd $OPENSHIFT_REPO_DIR ; 
        $PHP public/index.php phlycomic fetch all ; 
        $PHP public/index.php phlysimplepage cache clear --page=pages/comics 
    )
fi
</code></pre></div>

<p>
    And here's one that runs on the quarter-hour, placed in the <code>minutely</code>
    directory:
</p>

<div class="example"><pre><code language="bash">
#!/bin/bash
MINUTES=`date +%M`

for i in "00" "15" "30" "45";do
    if [ "$MINUTES" == "$i" ];then
        (
            export PHP=/usr/local/zend/bin/php ;
            cd $OPENSHIFT_REPO_DIR ;
            $PHP public/index.php githubfeed fetch 
        )
    fi
done
</code></pre></div>

<p>
    The point is that if you need more specificity, push the script into the 
    next more specific directory, and test against the time of execution.
</p>

<h2>Naked Domains</h2>

<p>
    Naked domains are domains without a preceding subdomain. In my case, this
    means "mwop.net", vs. "www.mwop.net".
</p>

<p>
    The problem that cloud hosting presents is that the IP address on which you
    are hosted can change at any time, for a variety of reasons. As such, you
    typically cannot use DNS A records to point to your domain; the recommendation
    is to use a CNAME record that points the domain to a "virtual" domain 
    registered with your cloud hosting provider.
</p>

<p>
    However, most domain registrars and DNS providers do not let you do this for
    a naked domain, particularly if you also have MX or other records associated
    with that naked domain.
</p>

<p>
    Some registrars will allow you to forward the A record to a subdomain. I tried
    this, but had limited success; I personally found that I ended up in an infinite
    loop situation when doing the DNS lookup.
</p>

<p>
    Another solution is to have a redirect in place for your naked domain to the
    subdomain, which can then be a CNAME record. Typically, this would require you
    have a web server under your control with a fixed IP that then simply redirects
    to the subdomain. Fortunately, there's an easier solution: <a 
    href="http://wwwizer.com/naked-domain-redirect">wwwizer</a>. You simply point
    your naked domain A record to the wwwizer IP address, and they will do a 
    redirect to your <code>www</code> subdomain.
</p>

<p>
    I implemented wwwizer on my domain (which is why you'll see "www.mwop.net" in
    your location bar), and it's been working flawlessly since doing so.
</p>

<h4>Private repositories</h4>

<p>
    I keep my critical site settings in a private repository, which allows me 
    to version them while keeping the credentials they hold out of the public eye.
    This means, however, that I need to use <a href="https://help.github.com/articles/managing-deploy-keys">GitHub deploy keys</a> on my server
    in order to retrieve changes.
</p>

<p>
    This was simple enough: I created an <code>ssh</code> subdirectory in my
    <code>$OPENSHIFT_DATA_DIR</code> directory, and generated a new SSH keypair.
</p>

<p>
    The problem was telling SSH to <em>use</em> this key when fetching changes.
</p>

<p>
    The solution is to use a combination of <code>ssh-agent</code> and <code>ssh-add</code>,
    and it looks something like this:
</p>

<div class="example"><pre><code language="bash">
#!/bin/bash
ssh-agent `ssh-add $OPENSHIFT_DATA_DIR/ssh/github-key && (
    cd $OPENSHIFT_DATA_DIR/config ; 
    git fetch origin ; 
    git rebase origin/mwop.net.config
)`
</code></pre></div>

<p>
    After testing the above, I put this in a <code>pre_build</code> script in 
    my OpenShift configuration so that I can autoupdate my private 
    configuration on each build. However, I discovered a new problem: when
    a build is being done, the <code>ssh-agent</code> is not available, which
    means the above cannot be executed. I'm still trying to find a solution.
</p>

<h2>Fin</h2>

<p>
    I'm pretty happy with the move. I don't have to do anything special
    to automate deployment, and all my cronjobs and deployment scripts are now
    self-contained in the repository, which makes my site more portable.
    While a few things could use more documentation, all the pieces are there
    and discoverable with a small amount of work.
</p>

<p>
    I'll likely give some other PaaS providers a try in the future, but for 
    the moment, I'm quite happy with the functionality and flexibility of 
    OpenShift.
</p>

<h4>Footnotes</h4>

<ul>
    <li id="f1">Zend Server's JobQueue can also be used as a cron replacement, 
    but I was not keen on exposing the job functionality via HTTP.</li>
</ul>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On php-fig and Shared Interfaces</title>
      <pubDate>Thu, 20 Dec 2012 20:23:00 +0000</pubDate>
      <link>http://mwop.net/blog/2012-12-20-on-shared-interfaces.html</link>
      <guid>http://mwop.net/blog/2012-12-20-on-shared-interfaces.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    This is a post I've been meaning to write for a long time, and one requested
    of me personally by <a href="http://www.rooftopsolutions.nl/blog/">Evert 
    Pot</a> during the Dutch PHP Conference in June 2012. It details some observations
    I have of php-fig, and hopefully will serve as a record of why I'm not
    directly participating any longer.
</p>

<p>
    I was a founding member of the <a href="http://www.php-fig.org/">Framework 
    Interoperability Group</a>, now called "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.
</p>

<p>
    The first "standard" that came from this was <a 
    href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md">PSR-0</a>, 
    which promoted a standard class naming convention that uses a 1:1 relationship 
    between the namespace and/or vendor prefix and the directory hierarchy, and the 
    class name and the filename in which it lives. To this day, there are both 
    those who hail this as a great step forward for cooperation, and simultaneously 
    others who feel it's a terrible practice. 
</p>

<p>
    And then nothing, for years. But a little over a year ago, there was a new 
    push by a number of folks wanting to do more. Paul Jones did a remarkable 
    job of spearheading the next <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md">two</a> 
    <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md">standards</a>, 
    which centered around coding style. Again, just like with PSR-0, we had 
    both those feeling it was a huge step forward, and those who loathe the 
    direction.
</p>

<p>
    What was interesting, though, was that once we started seeing some new energy
    and momentum, it seemed that <em>everyone</em> wanted a say. And we started 
    getting dozens of folks a week asking to be voting members, and new proposal
    after new proposal. Whether or not somebody likes an existing standard, they
    want to have backing for a standard they propose.
</p>

<p>
    And this is when we started seeing proposals surface for shared interfaces, first
    around caching, and now around logging (though the latter is the first up for
    vote).
</p><h2>Shared Interfaces</h2>

<p>
    The idea around shared interfaces is simple: if we can come to a consensus on
    the basic interface for a common application task, libraries and frameworks
    can typehint on that shared interface, allowing developers to drop in the 
    implementation of their choosing -- or even a standard, reference implementation.
    The goal is to prevent Not Invented Here (NIH) syndrome, as well as to make
    it simpler to re-use components between one library and another. As an example,
    if you're using Framework A, and it has a caching library, and you're consuming
    ORM B, you'd be able to pass the same cache object to the ORM as you use in the
    framework.
</p>

<p>
    Great goals, really.
</p>

<p>
    But I'm not sure I buy into them.
</p>

<h2>Problems</h2>

<p>
    First, I agree that NIH is a problem.
</p>

<p>
    Second, I <em>also</em> think there's space for <em>multiple 
    implementations</em> of any given component. Often there are different 
    approaches that different authors will take: one might focus on 
    performance, another on having multiple adapters for providing different 
    capabilities, etc. Sometimes having a different background will present 
    different problem areas you want to resolve. As such, having multiple 
    implementations can be a very good thing; developers can look at what each 
    provides, and determine which solves the particular issues presented in the 
    current project.
</p>

<p>
    Because of this latter point, I have my reservations about shared interfaces.
</p>

<p>
    What if a particular approach requires deviating from the shared interface in 
    order to accomplish its goals? Additionally, in order to keep the greatest
    amount of compatibility between projects, shared interfaces tend to be so
    generic that specific implementations require developers to do a ton of manual
    type checking and munging of parameters, leading to more overhead, more difficulty
    testing and maintaining, and more difficulty documenting and understanding.
</p>

<p>
    As an example, consider the following (made up) signature for a log method:
</p>

<div class="example"><pre><code language="php">
public function log($message, array $context = null);
</code></pre></div>

<p>
    What if your library supports an idea of priorities? Where would that 
    information go in the above signature -- and would that differ between 
    libraries -- would one library use the key for a completely different 
    purpose? What about logging objects -- the signature doesn't say you can't, 
    but how would I know if a specific implementation supports it, and won't 
    blow up if I do pass one? Why must the <code>$context</code> be an array -- 
    why won't any <code>Traversable</code> or <code>ArrayAccess</code> object 
    work?
</p>

<p>
    Basically, by being overly generic, the signature becomes a liability for
    those implementing the interface; it prevents meaningful interoperability
    and leads to splintering implementations.
</p>

<p><em>
    (Please note: the above is completely fictional and has no bearing
    on current proposed or accepted standards. It is a thought exercise
    only.)
</em></p>

<p>
    Furthermore, if a given project writes their own implementation of a 
    component, and it has specialized features, why would they want to typehint
    on a generic, shared interface that doesn't implement those features? This
    would be counter-intuitive, as the project would then need to either check on
    additional interfaces for the specialized capabilities, duck-type, etc. --
    all of which make for more maintenance and code.
</p>

<p>
    In summary, my primary problem with the idea of shared interfaces is that I 
    feel there is always room for new thinking and ideas in any given problem 
    space, and that this thinking should not be restricted by what already 
    exists. Secondarily, I feel that it's okay for a given project to be 
    selective about what capabilities it requires for its internal consumption 
    and consistency, and should not limit itself to a standardized interface.
</p>

<h2>But, but, SHARING</h2>

<p>
    <em>Remember, the first point I made was that I think NIH is a 
    problem.</em> How do I reconcile that with a firm stance against shared 
    interfaces?
</p>

<p>
    Easy: <a href="http://en.wikipedia.org/wiki/Bridge_pattern">bridges</a> 
    and/or <a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapters</a>.
</p>

<p>
    Let's go back to that example of Framework A, its caching library, and working
    with ORM B.
</p>

<p>
    Let's assume that ORM B defines an interface for caching, and let's say it
    looks like this:
</p>

<div class="example"><pre><code language="php">
interface CacheInterface
{
    public function set($key, $data);
    public function has($key);
    public function get($key);
}
</code></pre></div>

<p>
    Furthermore, we'll assume that the expected parameter values and return types
    are documented.
</p>

<p>
    What we as a consumer of both Framework A and ORM B can do is build an 
    <em>implementation</em> of <code>CacheInterface</code> that accepts a cache
    instance from Framework A, and proxies the various interface methods to that
    instance.
</p>

<div class="example"><pre><code language="php">
class FrameworkACache implements CacheInterface
{
    protected $cache;

    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    public function set($key, $data)
    {
        $item = new CacheItem($key, $data);
        $this->cache->setItem($item);
    }

    public function has($key)
    {
        return $this->cache->exists($key);
    }

    public function get($key)
    {
        $item = $this->cache->getItem($key);
        return $item->getData();
    }
}
</code></pre></div>

<p>
    Assuming your code is well-decoupled, and you're using some sort of Inversion of
    Control container, you can likely create a factory for your ORM that will grab
    the above class, with the cache injected, and inject it into the ORM instance. 
    Yes, it's a bit more work, but it's difficult to question the end result: 
    shared caching between the framework and the ORM - and no need for shared 
    interfaces, nor any need to sacrifice features within the framework or the 
    ORM.
</p>

<h2>Sharing is good, developing solutions is better</h2>

<p>
    I think the core idea of the php-fig group is sound: <em>let's all start thinking
    about how we can make it easier to operate with each other</em>. That said, my 
    thoughts on how to accomplish that goal have changed significantly, and 
    boil down to:
</p>

<ul>
    <li>Use naming conventions that will reduce collisions (i.e., use 
        per-project vendor prefixes/namespaces)</li>
    <li>Use semantic versioning</li>
    <li>Keep your installation packages segregated</li>
    <li>Have a simple, discoverable way to autoload</li>
    <li>Provide interfaces for anything that could benefit from alternate implementations</li>
    <li>Don't write code that has side-effects in the global namespace 
        (including altering PHP settings or superglobals)</li>
</ul>

<p>
    Following these principals, you can play nice with each other, while still 
    fostering innovative and differentiating solutions to shared problems.
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>PHP Master Series on Day Camp For Developers</title>
      <pubDate>Tue, 18 Dec 2012 20:24:00 +0000</pubDate>
      <link>http://mwop.net/blog/2012-12-18-php-master-series.html</link>
      <guid>http://mwop.net/blog/2012-12-18-php-master-series.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    <a href="http://blog.calevans.com">Cal Evans</a> has organized another 
    DayCamp4Developers event, this time entitled "<a 
    href="http://blog.calevans.com/2012/11/19/php-master-series-vol-1">PHP 
    Master Series, Volume 1</a>". I'm honored to be an invited speaker for this 
    first edition, where I'll be presenting my talk, "Designing Beautiful Software".
</p>

<p>
    Why would you want to participate? Well, for one, because you can interact directly
    with the various speakers during the presentations. Sure, you can likely find the slide
    decks elsewhere, or possibly even recordings. But if we all do our jobs right, we'll
    likely raise more questions than answers; if you attend, you'll get a chance to ask
    some of your questions immediately, <em>and we may even answer them!</em>
</p>

<p>
    On top of that, this is a fantastic lineup of speakers, and, frankly, not a lineup 
    I've ever participated in. In a typical conference, you'd likely see one or two of
    us, and be lucky if we weren't scheduled against each other; if you attend 
    this week, you'll get to see us all, back-to-back. 
</p>

<p>
    What else will you be doing this Friday, anyways, while <a 
    href="http://en.wikipedia.org/wiki/2012_phenomenon">you wait for the end of the 
    world?</a>
</p>

<p>
    So, do yourself a favor, and <a 
    href="http://phpmasterseriesv1.eventbrite.com/">register today</a>!
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>My ZendCon Beautiful Software Talk</title>
      <pubDate>Sat, 17 Nov 2012 13:53:00 +0000</pubDate>
      <link>http://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html</link>
      <guid>http://mwop.net/blog/2012-11-17-zendcon-beautiful-software.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    Once again, I spoke at <a href="http://www.zendcon.com/">ZendCon</a> 
    this year; in talking with <a href="http://twitter.com/chwenz">Christian Wenz</a>,
    we're pretty sure that the two of us and <a href="http://andigutmans.blogspot.com">Andi</a>
    are the only ones who have spoken at all eight events.
</p>

<p>
    Unusually for me, I did not speak on a Zend Framework topic, and had
    only one regular slot (I also co-presented a Design Patterns tutorial
    with my team). That slot, however, became one of my favorite talks I've
    delivered: "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.
</p>

<p>
    I discovered today that not only was it recorded, but it's been <a href="http://youtu.be/mQsQ6QZ4dGg">posted
    on YouTube</a>:
</p>

<iframe width="420" height="315" src="http://www.youtube.com/embed/mQsQ6QZ4dGg" frameborder="0" allowfullscreen></iframe><p>
    I've also <a href="/slides/2012-10-25-BeautifulSoftware/BeautifulSoftware.html">posted the slides</a>.
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On Visibility in OOP</title>
      <pubDate>Sat, 30 Jun 2012 15:00:00 +0000</pubDate>
      <link>http://mwop.net/blog/2012-06-28-oop-visibility.html</link>
      <guid>http://mwop.net/blog/2012-06-28-oop-visibility.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    I'm a big proponent of object oriented programming. OOP done right helps 
    ease code maintenance and enables code re-use.
</p>

<p>
    Starting in PHP, OOP enthusiasts got a whole bunch of new tools, and new
    tools keep coming into the language for us with each minor release. One
    feature that has had a huge impact on frameworks and libraries has been
    available since the earliest PHP 5 versions: visibility.
</p><h2>Theory</h2>

<p>
    The visibility keywords include <em>private</em>, <em>protected</em>, and 
    <em>public</em>, often referred to as <strong>PPP</strong>. There's an 
    additional keyword I often lump in with them, <em>final</em>.
</p>

<p>
    Public visibility is the default, and equivalent to the only visibility
    available to PHP prior to version 5: any member declared public is 
    accessible from any scope. This means the following:
</p>

<div class="example"><pre><code lang="php">
class Foo
{
    public $bar = 'bar';

    public function baz() 
    {
        // I can access within my own scope
        return $this->bar;
    }
}

class FooBar extends Foo
{
    public function doThat()
    {
        // I have access to members in my parent
        return $this->bar . $this->baz();
    }
}

$foo = new Foo();

// I can access public members from an instance
echo $foo->bar . $foo->baz();
</code></pre></div>

<p>
    Basically, public visibility means that I can access the member from 
    within the object, within an extending class, or from simply an instance.
</p>

<p>
    Protected visibility starts to tighten things down a little. With protected 
    visibility, only the class itself, or an extending class, can access the 
    member:
</p>

<div class="example"><pre><code lang="php">
class Foo
{
    protected $bar = 'bar';

    protected function baz() 
    {
        // I can access within my own scope
        return $this->bar;
    }
}

class FooBar extends Foo
{
    public function doThat()
    {
        // I can access protected members in my parent
        return $this->bar . $this->baz();
    }
}

$foo = new FooBar();

// This works, as I'm calling a public member of an extending class:
$foo->doThat();

// But these are both illegal:
echo $foo->bar . $foo->baz();
</code></pre></div>

<p>
    Protected visibility is nice for hiding things from those consuming your
    class. It can be used to hide implementation details, and to prevent direct
    modification of public properties -- something important to consider, if
    a property may be the product of calculation, or if a particular type is
    required.
</p>

<p>
    Private visibility locks things down further. With private visibility, the
    object member is only directly modifiable or callable within the declaring
    class.
</p>

<div class="example"><pre><code lang="php">
class Foo
{
    private $bar = 'bar';

    private function baz() 
    {
        // I can access within my own scope
        return $this->bar;
    }
}

class FooBar extends Foo
{
    public function doThat()
    {
        // These are both illegal
        return $this->bar . $this->baz();
    }
}

$foo = new FooBar();

// These are also both illegal:
echo $foo->bar . $foo->baz();
</code></pre></div>

<p>
    Private visibility is generally of interest for locking down algorithms. 
    For instance, if you know that a particular value or operation must not
    change, even in extending classes, declaring the member private ensures
    that extending classes cannot directly call it. 
</p>

<p>
    At any point, you can redeclare a property in an extending class using 
    equal or more public visibility. The effect of doing so depends on what
    the visibility of the member was in the parent class.
</p>

<ul>
    <li><p>In the case of a <em>public</em> property, if an extending class re-declares with 
        public visibility, any access to the member within the extending class or
        an instance of the extending class will see only the new declaration. </p>

        <div class="example"><pre><code lang="php">
class Foo
{
    public $bar = 'bar';

    public function baz() 
    {
        return $this->bar;
    }
}

class FooBar extends Foo
{
    public $bar = 'foobar';
}

$foo = new FooBar();
echo $foo->bar;   // "foobar"
echo $foo->baz(); // "foobar"
        </code></pre></div>
    </li>

    <li>
        <p>
            In the instance of a <em>protected</em> property, if the extending class 
            re-declares with either public or protected visibility, you get the
            same behavior as public -&gt; public.
        </p>

        <div class="example"><pre><code lang="php">
class Foo
{
    protected $bar = 'bar';

    public function baz() 
    {
        return $this->bar;
    }
}

class FooBar extends Foo
{
    public $bar = 'foobar';
}

$foo = new FooBar();
echo $foo->bar;   // "foobar"
echo $foo->baz(); // "foobar"
        </code></pre></div>
    </li>

    <li>
        <p>
            In the instance of a <em>private</em> property, things get interesting. The
            private value or method will be used for any access made within code
            declared in the parent class, but not overridden in the child. However,
            if the child class overrides any code, the value of the re-declared 
            instance will be used. This is far easier to understand via an example.
        </p>

        <div class="example"><pre><code lang="php">
class Foo
{
    private $bar = 'bar';
    private $baz = 'baz';

    public function baz() 
    {
        return $this->bar;
    }
}

class FooBar extends Foo
{
    protected $bar = 'foobar';
    private $baz = 'foobaz';

    public function myBaz() 
    {
        return $this->bar;
    }

    public function myBaz2()
    {
        return $this->baz;
    }
}

$foo = new FooBar();
echo $foo->baz();    // "bar"
echo $foo->myBaz();  // "foobar"
echo $foo->myBaz2(); // "foobaz"
        </code></pre></div>
    </li>
</ul>

<p>
    My personal takeaway from this is:
</p>

<ul>
    <li>Use <em>public</em> for members that are safe for anything to call.</li>
    <li>Use <em>protected</em> for anything you don't want called from instance methods, 
        not important to the public API (implementation details), and anything you 
        feel is safe for extending classes to muck about with.</li>
    <li>Use <em>private</em> for any important implementation details that could 
        adversely affect execution if overridden by an extending class.</li>
</ul>

<p>
    Those paying attention will note that I skipped <em>final</em>. Actually, I 
    saved that for last. Marking a class or method <em>final</em> tells PHP that
    the class or method may not be extended or re-declared/overridden. At all. I
    lump this with visibility, because it's another way of locking down access to
    an API; marking something <em>final</em> is saying, "you cannot extend this", 
    similar to using <em>private</em>, but without even the possibility of 
    redeclaring.
</p>

<h2>Applied</h2>

<p>
    What got me to thinking about all this was a turn of events with Zend 
    Framework 2. We've had an annotation parser since last summer. <a href="http://ralphschindler.com/">Ralph
    Schindler</a> developed it in order to facilitate automatic discovery of
    injection points for our Dependency Injection container. Classes could
    mark a method with the "Inject" annotation, and the various DI compilers
    would know that that method needed to be injected.
</p>

<div class="example"><pre><code lang="php">
use Zend\Di\Definition\Annotation\Inject;

class Foo
{
    protected $bar;

    /**
     * @Inject()
     * @param  Bar $bar
     * @return void
     */
    public function setBar(Bar $bar)
    {
        $this->bar = $bar;
    }
}

class Bar {}
</code></pre></div>

<p>
    Recently, part of our Forms RFC included a feature to allow creating
    forms and their related input filters by using annotations. Basically,
    this allows developers to hint on their domain entities how specific
    properties should be filtered, validated, and potentially represented
    at the form level.
</p>

<div class="example"><pre><code lang="php">
use Zend\Form\Annotation;

class Foo
{
    /**
     * @Annotation\Filter({"name":"StringTrim"})
     * @Annotation\Validator({"name":"Between","options":{"min":5,"max":20}})
     * @Annotation\Attributes({"type":"range"})
     */
    protected $bar;
}
</code></pre></div>

<p>
    One developer testing the support wanted to use a combination of <a 
    href="http://doctrine-project.org">Doctrine</a> annotations and ZF2 form
    annotations -- that way his entities could also describe validation and
    representation.
</p>

<p>
    I did some work to make this happen, and everybody was happy. Except then
    that same developer went to use that entity with Doctrine, and Doctrine's
    annotation parser started raising exceptions on all the ZF2 annotations.
</p>

<p>
    After some debate, I realized: (a) we were basically just making up syntax
    for our annotations; it'd be better to use an established syntax; but (b)
    we should still retain the ability to use arbitrary syntax, as we can't 
    really know what sorts of annotations developers may already be using.
</p>

<p>
    So, we decided to make our annotation component depend on the annotations
    support in Doctrine\\Common, 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 Doctrine\\Common annotation parser to parse annotations
    officially supported by ZF2.
</p>

<p>
    However, when I went to start making this happen, I ran into immediate issues.
</p>

<p>
    Remember how this post is about visibility? Well, the class I was directly
    interested in, <code>Doctrine\Common\Annotations\DocParser</code>, not only
    contains private members, but is marked <em>final</em>. 
</p>

<p>
    My immediate response was to start dissecting the class, cutting and pasting 
    the bits interesting to my solution into a new class in ZF2. I went down this
    route for several hours, gradually pulling in more and more methods as I
    discovered how far down the rabbit hole I needed to go to accomplish my task.
</p>

<p>
    But at the back of my head, I kept thinking this was a bad idea. If any
    patches ever came in for the original class, I'd need to port them into
    our ZF2 solution. And I couldn't help but think that I'd miss a crucial
    piece.
</p>

<p>
    So I started playing with its public API, to see if there were any shortcuts
    I might be able to take. And there were.
</p>

<p>
    The class has a public <code>parse()</code> method. Based on how Doctrine uses
    the code, I assumed I needed to pass a full PHP docblock in -- which ran
    counter to how I wanted to use the code. I wanted to pass in an annotation
    at a time. But when I looked closer, I realized that the parser didn't
    require a full docblock; any fragment would do.
</p>

<p>
    To make a long story short: I was able to feed the parser a single annotation
    at a time from ZF2's <code>AnnotationScanner</code>. This allowed me to build
    a very simple class that allows registering a set of annotations it can handle,
    and feeding it a single annotation string at a time to decide (a) if it supports
    it, and (b) to parse it and return the associated annotation object.
</p>

<p>
    In sum: because the class in question was marked final and had private 
    members, I found myself forced to think critically about what I wanted
    to accomplish, and then thoroughly understand the public API to see how
    I might accomplish that task without the ability to extend.
</p>

<h2>Conclusions</h2>

<p>
    Doctrine has a policy that encourages <a 
    href="http://en.wikipedia.org/wiki/Poka-yoke"><em>poka-yoke</em></a> solutions:
    code should be executable in a specific way. The policy was developed to
    both aid users (having multiple ways of doing something is often confusing),
    as well as to ease maintenance (fewer extension points means less liklihood
    of developers doing hard-to-debug things in extending code and reporting it
    back to the project). These have led them to heavily use <em>private</em>
    and <em>final</em> visibility.
</p>

<p>
    I've said it before, and I'll say it again: I feel that frameworks and libraries
    should use <em>private</em> and <em>final</em> sparingly. Over the years, I've
    seen code repurposed in simply wondrous ways -- largely due to keeping the
    code as open as possible to extension. I like to enable my users as much as 
    possible.
</p>

<p>
    That said, I can also see Doctrine's argument -- and can see where, while it
    can often be frustrating, it can also lead to potentially more sound and
    elegant solutions.
</p>

<p>
    I'll probably continue shying away from <em>private</em> and <em>final</em> 
    visibility, but I do plan to experiment with it more in the future. What 
    about you?
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>On Error Handling and Closures</title>
      <pubDate>Fri, 16 Dec 2011 16:26:18 +0000</pubDate>
      <link>http://mwop.net/blog/on-error-handling-and-closures.html</link>
      <guid>http://mwop.net/blog/on-error-handling-and-closures.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    The error suppression operator in PHP ("@") is often seen as a necessary 
    evil. Many, many low-level function will return a value indicating an error,
    but also raise an <code>E_NOTICE</code> or <code>E_WARNING</code> -- things
    you might be able to recover from, or conditions where you may want to raise
    an exception.
</p>

<p>
    So, at times, you find yourself writing code like this:
</p>

<div class="example"><pre><code lang="php">
if (false === ($fh = @fopen($filename, 'r'))) {
    throw new RuntimeException(sprintf(
        'Could not open file "%s" to read', $filename
    ));
}
</code></pre></div>

<p>
    Seems straight-forward enough, right? But it's wrong on so many levels.
</p><ul>
    <li>
        The error doesn't magically go away. If you've got PHP's log setup, 
        you're going to be getting a log entry each time the suppressed 
        statement errors.
    </li>

    <li>
        Error suppression is expensive. Like, really, really expensive. A 
        special error handler is registered to prevent the error propagating
        to the display (if <code>display_errors</code> is enabled), but errors
        are still sent to the log (as noted above). When done, the original
        error handler has to be restored.
    </li>

    <li>
        If you use things like <code>error_get_last()</code>, you may find that
        if you have many error suppressions, it returns something unrelated to
        the error that just occurred. 
    </li>

    <li>
        PHPUnit, anyone? Error suppression and PHPUnit do not play well 
        together. And there's a reason for that: often suppressed errors are
        indicative of bigger issues.
    </li>
</ul>

<p>
    So, how do you address it?
</p>

<p>
    PHP has two functions to assist with this: <code>set_error_handler()</code>
    and <code>restore_error_handler()</code>. The first takes a callable 
    argument, and optionally a mask of error levels to which it will respond;
    the second is used to return error handling to the previously set handler.
</p>

<div class="example"><pre><code lang="php">
function handleError($errno, $errmsg = '', $errfile = '', $errline = 0)
{
    throw new RuntimeException(sprintf(
        'Error reading file (in %s@%d): %s',
        $errfile, $errline, $errmsg
    ), $errno);
}

set_error_handler('handleError', E_WARNING);
$fh = fopen($filename, 'r');
restore_error_handler();
</code></pre></div>

<p>
    Traditionally, these have been a pain to use, as you have to create 
    individual functions or methods for handlers, and methods must have public
    visibility, even if the functionality is internal to the class.
</p>

<p>
    With PHP 5.3, we get a new option, however: closures. 
</p>

<p>
    With closures, error handlers are still a pain to use, but you now get to 
    scope the handlers directly in the context of the application flow. Let's
    look at an example:
</p>

<div class="example"><pre><code lang="php">
set_error_handler(
    function($error, $message = '', $file = '', $line = 0) use ($filename) {
        throw new RuntimeException(sprintf(
            'Error reading file "%s" (in %s@%d): %s',
            $filename, $file, $line, $message
        ), $error);
    },
    E_WARNING
);
$fh = fopen($filename, 'r');
restore_error_handler();

</code></pre></div>

<p>
    If you just want to ignore the error, it's even simpler:
</p>

<div class="example"><pre><code lang="php">
set_error_handler(function() { return true; }, E_NOTICE);
$contents = file_get_contents($filename);
restore_error_handler();
</code></pre></div>

<p>
    The code isn't necessarily succinct, which is one reason many gravitate
    towards using error suppression instead. However, it has the benefit of
    being context-sensitive and robust, which is always a good goal.
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Dependency Injection: An analogy</title>
      <pubDate>Fri, 25 Mar 2011 06:25:13 +0000</pubDate>
      <link>http://mwop.net/blog/260-Dependency-Injection-An-analogy.html</link>
      <guid>http://mwop.net/blog/260-Dependency-Injection-An-analogy.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
I've been working on a proposal for including service locators and dependency
injection containers in Zend Framework 2.0, and one issue I've had is trying to
explain the basic concept to developers unfamiliar with the concepts -- or with
pre-conceptions that diverge from the use cases I'm proposing.
</p>

<p>
In talking with my wife about it a week or two ago, I realized that I needed an
analogy she could understand; I was basically using her as my
<a href="http://en.wikipedia.org/wiki/Rubber_duck_debugging">rubber duck</a>. And it turned
out to be a great idea, as it gave me some good analogies.
</p><h2 id="toc_1.1">Dining Out</h2>

<p>
The analogies go like this: you walk into a burger join, and you're hungry.
</p>

<ul>
<li>
Dependency Injection is like ordering off the menu -- but specifying things
   like, "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.
</li>
<li>
Service Location is like ordering with substitutions, and having the waiter
   completely ignore the substitutions; you get what's on the menu, nothing
   more, nothing less.
</li>
</ul>

<p>
Now, when it comes to Zend Framework's version 1 releases, we've really got
neither. Our situation is more like a buffet or a kitchen -- you grab a little
of this, a little of that, and assemble your own burger. It's a lot more work.
</p>

<p>
Frankly, I'm lazy, and like my dinner brought to me... and if I want any
substitutions, I'd like those, too.
</p>

<h2 id="toc_1.2">Getting the Ingredients</h2>

<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.
</p>

<p>
There are two things to keep in mind: 
</p>

<ol>
<li>
you, the developer, define the dependencies up front
</li>
<li>
if you don't pull the object from the container, you're in charge
</li>
</ol>

<p>
Regarding the second point, it appears some developers think that with a DI
container in place, dependencies magically get injected in <em>every</em> object. But
that's simply not the case. If you use normal PHP:
</p>

<div class="example"><pre><code lang="php">
$o = new SomeClass();
</code></pre></div>

<p>
you'll get a new instance, just like always, configured only with any parameters
you pass in to the constructor or methods you call on it. It's only when you
retrieve the object from the DI container that you dependency injection takes
place; if you do that, you can always examine the DI configuration (which can
either be programmatic or via a configuration file) to determine what
dependencies were configured.
</p>

<p>
Basically, it's like the difference between making your own hamburger patty out
of fresh ground sirloin, and ordering Animal Style from In-N-Out.
</p>

<h2 id="toc_1.3">I'm done now</h2>

<p>
What's your favorite way of thinking of these concepts?
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Aspects, Filters, and Signals, Oh, My!</title>
      <pubDate>Fri, 14 Jan 2011 13:53:52 +0000</pubDate>
      <link>http://mwop.net/blog/251-Aspects,-Filters,-and-Signals,-Oh,-My!.html</link>
      <guid>http://mwop.net/blog/251-Aspects,-Filters,-and-Signals,-Oh,-My!.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
Last month, during <a href="http://phpadvent.org">PHP Advent</a>,
<a href="http://ohloh.net/accounts/gwoo">gwoo</a> wrote an interesting post on
<a href="http://phpadvent.org/2010/aspect-oriented-design-by-garrett-woodworth">
Aspect-Oriented Design</a>, or Aspect Oriented Programming (AOP) as it is more
commonly known. The article got me to thinking, and revisiting what I know about
AOP, Intercepting Filters, and Signal Slots -- in particular, what use cases I
see for them, what the state of current PHP offerings are, and where the future
may lie.
</p>

<p>
But first, some background is probably in order, as this is a jargon-heavy post.
</p><h2 id="toc_1.1">Aspect Oriented Programming</h2>

<p>
I was first introduced to AOP in 2006 via an <a href="http://www.phparch.com/magazine/2006-2/april/">April 2006 php|architect article by Dmitry Sheiko</a>. That article detailed adding calls at various
places in a method where you might want to hook into functionality -- for
instance, to log, cache, etc. Expanding on this, I considered other
possibilities: manipulating incoming arguments, validation, ACL checks,
implementing write-through caching strategies, and more. The approach is
daunting, however; typical, naive implementations lead to a lot of boiler-plate code:
</p>

<div class="example"><pre><code lang="php">
interface Listener
{
    public function notify($signal, $argv = null);
}

class Foo
{
    protected $listeners;

    public function attach($signal, Listener $listener)
    {
        $this-&gt;listeners[$signal][] = $listener;
    }

    public function doSomething($arg1, $arg2)
    {
        foreach ($this-&gt;listeners as $listener) {
            $listener-&gt;notify('preDoSomething', func_get_args());
        }
        
        // do some work
        
        foreach ($this-&gt;listeners as $listener) {
            $listener-&gt;notify('postDoSomething', $result);
        }
    }
}
</code></pre></div>

<p>
The article didn't go into any real details on how you might short-circuit the
filters or handle return values from them, and aspect handling itself was not detailed completely. As such, the code begins to add up, particularly if many
classes and/or methods implement the functionality. 
</p>

<h2 id="toc_1.2">Intercepting Filters</h2>

<p>
A similar concept to AOP is the idea of
<a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html">Intercepting</a> 
<a href="http://msdn.microsoft.com/en-us/library/ff647251.aspx">Filters</a>.
Like AOP, the idea is to separate cross-cutting concerns such as logging,
debugging, and more from the actual logic the component exposes. The difference
is that typically Intercepting Filters are language independent, have a standard
implementation in a given framework, and can be re-used.  The approach gwoo used
in his post falls more under this category.
</p>

<p>
<a href="http://lithify.me/">Lithium</a>, a PHP 5.3 framework and the reference for gwoo's
article, has a very intriguing approach. Instead of calling the filters
explicitly within the body of the code, they suggest that the body of the code
simply becomes one of the filters, via a closure:
</p>

<div class="example"><pre><code lang="php">
Dispatcher::applyFilter('run', function ($self, $params, $chain) {
    // do something...
    return $chain-&gt;next($self, $params, $chain);
});
</code></pre></div>

<p>
In Lithium, each filter is responsible for calling the next (each filter
receives the chain as its third and final argument); as soon as one doesn't call
<code>next()</code>, execution is stopped, and the result returned (or at least that's how
I read the source). You can call the chain either before or after the code you
want to execute in each filter; placement will determine whether it's a pre- or
a post-filter. The approach answers a number of the concerns I outlined
previously -- namely, standardization of approach, and the ability to
short-circuit execution.
</p>

<p>
The above example defines a filter that will run when the <code>run()</code> method of the
<code>Dispatcher</code> class is executed. <code>$self</code> will typically be the object instance,
<code>$params</code> an array of the parameters passed to the method, and <code>$chain</code> as
described above. The method itself will execute any filters -- typically with
something like this:
</p>

<div class="example"><pre><code lang="php">
use lithium/core/Object as BaseObject;

class Foo extends BaseObject
{
    public function doSomething($with, $these, $args)
    {
        $params = compact('with', 'these', 'args');
        
        return $this-&gt;_filter(__METHOD__, $params, function ($self, $params) {
            // do the actual work here
            return $result;
        });
    }
}
</code></pre></div>

<p>
(The <code>_filter()</code> method is defined in <code>lithium\core\Object</code>, and basically
passes a local, static chain of filters to Lithium's <code>Filter</code> class for
execution. <code>applyFilter()</code> from the previous example statically adds a callback
under the named method to the chain.)
</p>

<p>
This solution is elegant -- but I see some limitations:
</p>

<ul>
<li>
   First and foremost, I'm not particularly fond of the filtering functionality
   being via static methods on a single class; it introduces a hard-coded,
   hidden dependency. This means you cannot provide alternate filtering
   functionality without extending the class <em>consuming</em> the filters, nor
   without either extending the base filters implementation should you wish to
   provide a compatible API (for instance, to introduce an implementation that
   understands priorities).
   <br /><br />
   Additionally, the easiest way to implement filtering in Lithium is by
   extending the <code>lithium\core\Object</code> class -- I could find no examples
   elsewhere in the documentation that showed how you would compose the <code>Filters</code>
   implementation in your own objects. As such, the easiest way to compose
   filters is now via inheritance, which seems to be counter-productive to the
   whole rationale behind filtering, to my thinking.
</li>
<li>
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.)
</li>
<li>
Third, it's sometimes useful to have access to the return results of <em>all</em>
   the filters (not just the last executed); you may want to aggregate them in
   some way, or branch logic based on the various returns. 
</li>
<li>
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:
<div class="example"><pre><code lang="php">
Filters::add('SomeClass::doSomething', function ($method, $self, $params) {
    if (null !== ($content = cache_hit($params))) {
        return $content;
    }
    $content = Filters::next($method, $self, $params);
    return $content;
});
</code></pre></div>
   However, if you have several filters such as this, the order then becomes
   paramount, and that introduces new complexities.
   <br /><br />
   Another example would be with façade methods, where you may wish to introduce
   filters before and after each method call:
<div class="example"><pre><code lang="php">
    public function doSomeWorkflow($message)
    {
        $this-&gt;somePrivateMethod($message);
        $this-&gt;nextPrivateMethod($message);
        $this-&gt;lastPrivateMethod($message);
    }
</code></pre></div>
    <br /><br />
   (I can already hear <a href="http://nateabele.com/">Nate</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.)
</li>
<li>
Fifth, it's useful to be able to attach callbacks that are not aware of the
   chain. For instance, you may have code you've already written that works
   perfectly fine in a standalone situation -- e.g., a logger -- and you simply
   want to add it to the chain. In the Lithium paradigm, you'd need to
   <a href="http://en.wikipedia.org/wiki/Currying">curry</a> the calls in, instead of simply
   using the existing method:
<div class="example"><pre><code lang="php">
// This:
SomeClass::applyFilter('doSomething', function ($self, $params, $chain) use ($log) {
    $log-&gt;info($params['message'];
    $chain-&gt;next($self, $params, $chain);
});
// VS:
SomeClass::signals()-&gt;connect('doSomething', $log, 'info');
</code></pre></div>
   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.
</li>
</ul>
   
<p>
All in all, however, the approach Lithium provides is very good; it just doesn't
completely suit my tastes or use cases.
</p>

<h2 id="toc_1.3">Signal Slots</h2>

<p>
Interestingly, the capabilities I need are not far from what Lithium provides --
in fact, I'd argue that the Intercepting Filters of Lithium are actually
probably more akin to another pattern,
<a href="http://en.wikipedia.org/wiki/Signals_and_slots">Signal Slots</a>. 
</p>

<p>
With Signal Slots, your code emits <em>signals</em> (Lithium does this -- it emits the
name of the method being called); any handler, or <em>slot</em> (<em>filters</em> in Lithium),
connected to the signal is then executed. 
</p>

<p>
As such, you typically have some sort of signal "manager" object (the <code>Filters</code>
class in Lithium) that aggregates signals and attached slots; this manager is
then composed into the object emitting signals. For those of you familiar with
events in JavaScript or other event-driven languages, this should sound quite
familiar.
</p>

<p>
Such an approach looks like this:
</p>

<div class="example"><pre><code lang="php">
class Foo
{
    protected $signals;

    public function signals(SignalSlot $signals = null)
    {
        if (null === $signals) {
            // No argument? make sure we have a signal manager
            if (null === $this-&gt;signals) {
                $this-&gt;signals = new Signals(); // SignalSlot implementation
            }
        } else {
            // Compose in an instance of a signal manager
            $this-&gt;signals = $signals;
        }
        return $this-&gt;signals;
    }

    public function doSomething($with, $these, $args)
    {
        $this-&gt;signals()-&gt;emit('doSomething.pre', $this, $with, $these, $args);
        
        // do some work
        $this-&gt;signals()-&gt;emit('doSomething.during', $this, $with, $these, $args);

        // do some more work
        // This time, pass the result
        $this-&gt;signals()-&gt;emit('doSomething.post', $this, $result, $with, $these, $args);
        return $result;
    }
}

$f = new Foo();
$f-&gt;signals()-&gt;connect('doSomething.pre', $log, 'info');
$f-&gt;signals()-&gt;connect('doSomething.during', $validator, 'isValid');
$f-&gt;signals()-&gt;connect('doSomething.post', $indexer, 'index');
</code></pre></div>


<p>
Basically, a <code>SignalSlot</code> provides an object in which signals and their attached
slots are aggregated. This allows having a single manager for multiple signals
(which is similar to how Lithium's <code>Filters</code> class works), while also providing
a way to emit multiple signals from a single procedure. Additionally, since it
is simply an object, you can compose it in to classes that may emit signals --
without requiring inheritance.
</p>

<p>
This is the basic approach of the
<a href="https://github.com/zendframework/zf2/tree/master/library/Zend/SignalSlot">ZF2 SignalSlot implementation</a>, as well as that found in
<a href="http://components.symfony-project.org/event-dispatcher/">Symfony 2's Event Dispatcher</a> and
<a href="http://incubator.apache.org/zetacomponents/documentation/trunk/SignalSlot/tutorial.html">Zeta Components' SignalSlot component</a>. 
</p>

<p>
Both Symfony 2's Event Dispatcher and ZF2's <code>SignalSlot</code> component build in the
ability to short-circuit, Symfony via a <code>notifyUntil()</code> method, and ZF2 via an
<code>emitUntil</code> method. With ZF2, each time a signal is emitted, a
<code>ResponseCollection</code> is returned by the manager, containing an aggregate of all
slot responses. Calling <code>emitUntil()</code> will short-circuit execution of remaining
slots if a given slot returns a response that validates against given criteria;
at this point, the collection is marked as "stopped", and you can pull the
"last" response and return it:
</p>

<div class="example"><pre><code lang="php">
$responses = $this-&gt;signals()-&gt;emitUntil(function($response) {
    return ($response instanceof SpecificResultType);
}, 'doSomething.pre', $this, $with, $these, $args);
if ($responses-&gt;stopped()) {
    return $responses-&gt;last();
}
</code></pre></div>

<p>
This introduces extra code in the method emitting the signals -- but meets the
criteria that no given slot need be aware of the chain. 
</p>

<p>
The Signal Slot approach actually supports paradigms similar to those
illustrated in Lithium. For instance, I can make my method body a slot:
</p>

<div class="example"><pre><code lang="php">
class Foo
{
    protected $handlers = array();

    // ... skip signals composition ...
    
    public function doSomething($with, $these, $args)
    {
        $params = compact('with', 'these', 'args');
        
        // connect() returns a signal handler (slot); store it so that we only
        // ever attach it once...
        if (isset($this-&gt;handlers[__FUNCTION__])) {
            $this-&gt;handlers[__FUNCTION__] = $this-&gt;signals()-&gt;connect(__FUNCTION__, function($self, $params) {
                // do the work here!
            });
        }
        
        // Emit the signal, and return the last result
        return $this-&gt;signals()-&gt;emit(__FUNCTION__, $this, $params)-&gt;last();
    }
}
</code></pre></div>

<h2 id="toc_1.4">Concerns</h2>

<p>
Using Signal Slots and Intercepting Filters is not without its concerns, nor is
any given implementation perfect.
</p>

<ul>
<li>
Zeta Components does a fantastic job of handling signal slots.  However, you
   cannot short-circuit execution, nor introspect return values. It does offer
   two features neither ZF2 nor Symfony 2 offer (at this time): the ability to
   <em>statically</em> connect slots to signals, allowing you to wire without having an
   existing instance, nor even caring what object might emit the signal; and the
   ability to add a priority to slots, which allows you to alter the execution
   order. 
</li>
<li>
Lithium does a nice job of providing good standards (signals are method
   names; parameters are predictable for all handlers), but at the price of some
   flexibility (static implementation with no interface for alternate
   implementations; no ability to re-use existing methods and functions with
   differing signatures without currying). 
</li>
<li>
Symfony 2 offers short-ciruiting and flexibility in callbacks, but requires
   that you create an event object to pass to the Event Dispatcher, making the
   usage slightly more verbose, and offers no standardization of signal naming. 
</li>
<li>
ZF2's <code>SignalSlots</code> offer similar benefits (and drawbacks) to Symfony 2's
   implementation, provides standardization of the signal manager response,
   allows registering classes that self-register with the signal handler, but
   lacks static wiring capabilities or prioritization.
</li>
</ul>

<p>
On a more abstract level, signal slots and intercepting filters can lead to
difficulties in learning and mastering code that use them:
</p>

<ul>
<li>
How are signals named?
</li>
<li>
How do you document the parameters available to slots/filters?
</li>
<ul>
<li>
How can those using IDEs discover available signals? and the arguments
      expected?
</li>
</ul>
<li>
Where does the wiring occur?
</li>
<ul>
<li>
For instance, if any wiring is automated, this can potentially lead to
      more difficulty in debugging.
</li>
<li>
If done manually, when, and where? 
</li>
</ul>
<li>
What happens if a slot doesn't receive arguments it needs, or cannot handle
   the arguments it receives?
</li>
</ul>

<p>
In short, while they solve many problems, the implementations also introduce new
concerns -- though this will be true of any extension system, in my experience.
</p>

<h2 id="toc_1.5">Conclusions</h2>

<p>
I personally am a huge fan of Intercepting Filters and Signal Slots. I think
they can make code easier to extend, by providing a standard methodology for
introducing cross-cutting concerns without requiring class extension. They can
also make code quite expressive -- sometimes at the cost of readability -- by
introducing functional programming paradigms. 
</p>

<p>
If you have not investigated these concepts or components before, I highly
recommend doing so; I think they play a fundamental role in the next generation
of PHP frameworks.
</p>

<h2 id="toc_1.6">Caveats</h2>

<p>
I am not an expert, nor well-versed, in all the frameworks listed here, and as
such, some of the information may be incorrect or incomplete. I am the
author of ZF2's current Signal Slot implementation, and am still working on
improvements to it.
</p>

<h2>Updates</h2>
<ul>
    <li><b>2011-01-10 11:35Z-05:00</b> Cal Evans found the original php|architect article I referenced, and I've revised some of the assessments based on re-reading it, as well as linked to the issue.</li>
</ul>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Setting up your Zend_Test test suites</title>
      <pubDate>Sat, 13 Sep 2008 13:37:40 +0000</pubDate>
      <link>http://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html</link>
      <guid>http://mwop.net/blog/190-Setting-up-your-Zend_Test-test-suites.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    Now that <a href="http://framework.zend.com/manual/en/zend.test.html">Zend_Test</a>
    has shipped, developers are of course asking, "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.
</p><p>
    <a href="http://phpunit.de">PHPUnit</a> offers a variety of methods for
    setting up test suites, some trivial and some complex. The Zend Framework
    test suite, for instance, goes for a more complex route, adding
    component-level suites that require a fair amount of initial setup, but
    which allow us fairly fine-grained control.
</p>

<p>
    However, testing and test automation should be easy and the complex approach
    is overkill for most of our applications. Fortunately, PHPUnit offers some
    other methods that make doing so relatively simple. The easiest method is to
    use an <a href="http://www.phpunit.de/pocket_guide/3.2/en/appendixes.configuration.html">XML configuration file</a>.
</p>

<p>
    As an example, consider the following:
</p>

<div class="example"><pre><code lang="xml">
&lt;phpunit&gt;
    &lt;testsuite name=\&quot;My Test Suite\&quot;&gt;
        &lt;directory&gt;./&lt;/directory&gt;
    &lt;/testsuite&gt;

    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory suffix=\&quot;.php\&quot;&gt;../library/&lt;/directory&gt;
            &lt;directory suffix=\&quot;.php\&quot;&gt;../application/&lt;/directory&gt;
            &lt;exclude&gt;
                &lt;directory suffix=\&quot;.phtml\&quot;&gt;../application/&lt;/directory&gt;
            &lt;/exclude&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;

    &lt;logging&gt;
        &lt;log type=\&quot;coverage-html\&quot; target=\&quot;./log/report\&quot; charset=\&quot;UTF-8\&quot;
            yui=\&quot;true\&quot; highlight=\&quot;true\&quot;
            lowUpperBound=\&quot;50\&quot; highLowerBound=\&quot;80\&quot;/&gt;
        &lt;log type=\&quot;testdox-html\&quot; target=\&quot;./log/testdox.html\&quot; /&gt;
    &lt;/logging&gt;
&lt;/phpunit&gt;
</code></pre></div>

<p>
    First thing to note, relative paths are relative to the configuration file.
    This allows you to run your tests from anywhere in your tests tree, Second,
    providing a <code>directory</code> directive to the
    <code>testsuite</code> directive scans for all files ending in "Test.php" in
    that directory, meaning you don't have to keep a list of your test cases
    manually. It's a great way to automate the suite. Third, the filter
    directive allows us to determine what classes to include and/or exclude
    from coverage reports. Finally, the <code>logging</code> directive lets us
    specify what kinds of logs to create and where.
</p>

<p>
    Drop the above into "tests/phpunit.xml" in your application, and you can
    start writing test cases and running the suite immediately, using the
    following command:
</p>

<div class="example"><pre><code lang="text">
% phpunit --configuration phpunit.xml
</code></pre></div>

<p>
    I like to group my test cases by type. I have controllers, models, and often
    library code, and need to keep the tests organized both on the filesystem as
    well as for running the actual tests. There are two things I do to
    facilitate this.
</p>

<p>
    First, I create directories. For instance, I have the following hierarchy in
    my test suite:
</p>

<div class="example"><pre><code lang="text">
tests/
    phpunit.xml
    TestHelper.php
    controllers/
        IndexControllerTest.php (contains IndexControllerTest)
        ErrorControllerTest.php (contains ErrorControllerTest)
        ...
    models/
        PasteTest.php           (contains PasteTest)
        DbTable/
            PasteTest.php       (contains DbTable_PasteTest)
        ...
    My/
        Form/
            Element/
                SimpleTextareaTest.php
</code></pre></div>

<p>
    "controllers/" contains my controllers, "models/" contains my models. If I
    were developing a modular application, I'd have something like
    "blog/controllers/" instead. Library code is given the same hierarchy as is
    found in my "library/" directory.
</p>

<p>
    Second, I use docblock annotations to group my tests. I add the following to
    my class-level docblock in my controller test cases:
</p>

<div class="example"><pre><code lang="php">
/**
 * @group Controllers
 */
</code></pre></div>

<p>
    Models get the annotation "@group Models", etc. This allows me to run
    individual sets of tests on demand:
</p>

<div class="example"><pre><code lang="text">
% phpunit --configuration phpunit.xml --group Controllers
</code></pre></div>

<p>
    You can specify multiple @group annotations, which means you can separate
    tests into modules, issue report identifiers, etc; additionally, you can add
    the annotations to individual test methods themselves to have really
    fine-grained test running capabilities.
</p>

<p>
    Astute readers will have noticed the "TestHelper.php" file in that directory
    listing earlier, and will be wondering what that's all about.
</p>

<p>
    A test suite needs some environmental information, just like your
    application does. It may need a default database adapter, altered
    include_paths, autoloading set up, and more. Here's what my TestHelper.php
    looks like:
</p>

<div class="example"><pre><code lang="php">
&lt;?php
/*
 * Start output buffering
 */
ob_start();

/*
 * Set error reporting to the level to which code must comply.
 */
error_reporting( E_ALL | E_STRICT );

/*
 * Set default timezone
 */
date_default_timezone_set('GMT');

/*
 * Testing environment
 */
define('APPLICATION_ENV', 'testing');

/*
 * Determine the root, library, tests, and models directories
 */
$root        = realpath(dirname(__FILE__) . '/../');
$library     = $root . '/library';
$tests       = $root . '/tests';
$models      = $root . '/application/models';
$controllers = $root . '/application/controllers';

/*
 * Prepend the library/, tests/, and models/ directories to the
 * include_path. This allows the tests to run out of the box.
 */
$path = array(
    $models,
    $library,
    $tests,
    get_include_path()
);
set_include_path(implode(PATH_SEPARATOR, $path));

/**
 * Register autoloader
 */
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

/**
 * Store application root in registry
 */
Zend_Registry::set('testRoot', $root);
Zend_Registry::set('testBootstrap', $root . '/application/bootstrap.php');

/*
 * Unset global variables that are no longer needed.
 */
unset($root, $library, $models, $controllers, $tests, $path);
</code></pre></div>

<p>
    The above ensures that my APPLICATION_ENV constant is set appropriately,
    that error reporting is appropriate for tests (i.e., I want to see
    <em>all</em> errors), and that autoloading is enabled. Additionally, I place
    a couple items in my registry -- the bootstrap and test root directory.
</p>

<p>
    In each test case file, I then do a require_once on this file. In future
    versions of PHPUnit, you'll be able to specify a bootstrap file in your
    configuration XML that gets pulled in for each test case, and you'll be able
    to even further automate your testing environment setup.
</p>

<p>
    Hopefully this will get you started with your application testing; what are
    you waiting for?
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
    <item>
      <title>Migrating OOP Libraries and Frameworks to PHP 5.3</title>
      <pubDate>Mon, 07 Jul 2008 03:49:14 +0000</pubDate>
      <link>http://mwop.net/blog/181-Migrating-OOP-Libraries-and-Frameworks-to-PHP-5.3.html</link>
      <guid>http://mwop.net/blog/181-Migrating-OOP-Libraries-and-Frameworks-to-PHP-5.3.html</guid>
      <author>me@mwop.net (Matthew Weier O'Phinney)</author>
      <dc:creator>Matthew Weier O'Phinney</dc:creator>
      <content:encoded><![CDATA[<p>
    With PHP 5.3 coming up on the horizon, I'm of course looking forward to
    using namespaces. Let's be honest, who wants to write the following line?
</p>

<div class="example"><pre><code lang="php">
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
</code></pre></div>

<p>
    when the more succinct:
</p>

<div class="example"><pre><code lang="php">
$viewRenderer = HelperBroker::getStaticHelper('viewRenderer');
</code></pre></div>

<p>
    could be used? (Assuming you've executed <code>'use
    Zend::Controller::Action;'</code> somewhere earlier...)
</p>

<p>
    However, while namespaces will hopefully lead to more readable code,
    particularly code in libraries and frameworks, PHP developers will finally
    need to start thinking about sane standards for abstract classes and
    interfaces. 
</p><p>
    For instance, we've been doing things like the following in Zend
    Framework:
</p>

<ul>
     <li>Zend_Controller_Request_Abstract</li>
     <li>Zend_View_Interface</li>
</ul>

<p>
    These conventions make it really easy to find Abstract classes and
    Interfaces using <code>find</code> or <code>grep</code>, and also are
    predictable and easy to understand. However, they won't play well with
    namespaces. Why? Consider the following:
</p>

<div class="example"><pre><code lang="php">
namespace Zend::Controller::Request

class Http extends Abstract
{
    // ...
}
</code></pre></div>

<p>
    Spot the problem? 'Abstract' is a reserved word in PHP. The same goes for
    interfaces. Consider this particularly aggregious example:
</p>


<div class="example"><pre><code lang="php">
namespace Zend::View

abstract class Abstract implements Interface
{
    // ...
}
</code></pre></div>

<p>
    We've got two reserved words there: Abstract <em>and</em> Interface.
</p>

<p>
    <a href="http://php100.wordpress.com/">Stas</a>, Dmitry, and I sat down to
    discuss this a few weeks ago to come up with a plan for migrating to PHP
    5.3. In other OOP languages, such as Python, C#, interfaces are denoted by
    prefixing the interface with a capital 'I'; in the example above, we would
    then have <code>Zend::View::IView</code>. We decided this would be a sane
    step, as it would keep the interface within the namespace, and visually
    denote it as well. We also decided that this convention made sense for
    abstract classes: <code>Zend::View::AView</code>. So, our two examples
    become:
</p>

<div class="example"><pre><code lang="php">
namespace Zend::Controller::Request

class Http extends ARequest
{
    // ...
}
</code></pre></div>

<p>and:</p>

<div class="example"><pre><code lang="php">
namespace Zend::View

abstract class AView implements IView
{
    // ...
}
</code></pre></div>

<p>
    Another thing that looks likely to affect OOP libraries and frameworks is
    autoloading, specifically when using exceptions. For instance, consider
    this:
</p>

<div class="example"><pre><code lang="php">
namespace Foo::Bar

class Baz
{
    public function status()
    {
        throw new Exception(\&quot;This isn't what you think it is\&quot;);
    }
}
</code></pre></div>

<p>
    You'd expect the exception to be of class <code>Foo::Bar::Exception</code>,
    right? Wrong; it'll be a standard <code>Exception</code>. To get around
    this, you can do the following:
</p>

<div class="example"><pre><code lang="php">
namespace Foo::Bar

class Baz
{
    public function status()
    {
        throw new namespace::Exception(\&quot;This is exactly what you think it is\&quot;);
    }
}
</code></pre></div>

<p>
    By using the <code>namespace</code> keyword, you're telling the PHP engine
    to explicitly use the Exception class from the current namespace. I also
    find this to be more semantically correct -- it's more explicit that you're
    throwing a particular type of exception, and makes it easy to find and
    replace these with alternate declarations at a later date.
</p>

<p>
    I'd like to recommend other libraries adopt similar standards -- they're
    sensible, and fit already within PEAR/Horde/ZF coding standards. What say
    you?
</p>]]></content:encoded>
      <slash:comments>0</slash:comments>
    </item>
  </channel>
</rss>
