<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>xdissent.com &#8623; Articles</title>
	<atom:link href="http://xdissent.com/feed/articles/" rel="self" type="application/rss+xml" />
	<link>http://xdissent.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sat, 20 Feb 2010 00:07:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Mimicking Python Descriptors in PHP</title>
		<link>http://xdissent.com/2010/01/15/mimicking-python-descriptors-in-php/</link>
		<comments>http://xdissent.com/2010/01/15/mimicking-python-descriptors-in-php/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 00:55:56 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[descriptors]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=112</guid>
		<description><![CDATA[
So you&#8217;ve been working in Python for a year and then along comes a PHP gig
that you just can&#8217;t pass up. All of a sudden you&#8217;re realizing just how much
you miss some of the familiar Pythonisms you&#8217;ve come to rely on. One such
feature that is lacking in PHP is the concept of descriptors. Fortunately,
it&#8217;s possible [...]]]></description>
			<content:encoded><![CDATA[
<p>So you&#8217;ve been working in Python for a year and then along comes a PHP gig
that you just can&#8217;t pass up. All of a sudden you&#8217;re realizing just how much
you miss some of the familiar <a class="reference external" href="http://pythonism.wordpress.com">Pythonisms</a> you&#8217;ve come to rely on. One such
feature that is lacking in PHP is the concept of <a class="reference external" href="http://docs.python.org/reference/datamodel.html#descriptors">descriptors</a>. Fortunately,
it&#8217;s possible to pretty closely simulate their behaviour in PHP with just
a few special interfaces and classes.</p>
<span id="more-112"></span>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#mind-blowing" id="id1">Mind Blowing</a><ul>
<li><a class="reference internal" href="#object-instances" id="id2">object instances&#8230;</a></li>
<li><a class="reference internal" href="#posing-as-dynamic-properties" id="id3">posing as dynamic properties&#8230;</a></li>
<li><a class="reference internal" href="#which-are-defined-on-a-class" id="id4">which are defined on a <em>class</em>&#8230;</a></li>
<li><a class="reference internal" href="#evaluated-at-runtime-by-a-method-on-the-descriptor-object-itself" id="id5">evaluated at runtime by a method on the descriptor object itself&#8230;</a></li>
<li><a class="reference internal" href="#that-are-accessible-through-either-an-object-instance" id="id6">that are accessible through <em>either</em> an object instance&#8230;</a></li>
<li><a class="reference internal" href="#or-statically-through-a-property-on-the-the-class-itself" id="id7">or <em>statically</em> through a property on the the class itself!</a></li>
</ul>
</li>
<li><a class="reference internal" href="#meet-the-family" id="id8">Meet the Family</a></li>
<li><a class="reference internal" href="#the-gotchas" id="id9">The Gotchas</a></li>
<li><a class="reference internal" href="#the-payoff" id="id10">The Payoff</a><ul>
<li><a class="reference internal" href="#easy-class-wide-caching" id="id11">Easy (Class-wide) Caching</a></li>
<li><a class="reference internal" href="#memory-footprint" id="id12">Memory Footprint</a></li>
<li><a class="reference internal" href="#cleaner-than-the-alternatives" id="id13">Cleaner Than the Alternatives</a></li>
<li><a class="reference internal" href="#true-object-oriented-design" id="id14">True Object Oriented Design</a></li>
</ul>
</li>
<li><a class="reference internal" href="#conclusion" id="id15">Conclusion</a></li>
</ul>
</div>
<div class="section" id="mind-blowing">
<h2>Mind Blowing</h2>
<p>For the uninitiated, there are <a class="reference external" href="http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/">a few</a> <a class="reference external" href="http://users.rcn.com/python/download/Descriptor.htm">great</a> <a class="reference external" href="http://mypythonnotes.wordpress.com/2008/07/05/python-descriptors/">articles</a> online that go
into great detail about what Python descriptors <em>are</em>, and what they can <em>do</em>.
Descriptors are a notoriously mind boggling topic that has left many a
curious developer cross-eyed and drooling, and usually more confused than
we he started. But they&#8217;re simple to understand, really: They&#8217;re just object
instances posing as dynamic properties which are defined on a <em>class</em>,
evaluated at runtime by a method on the descriptor object itself, that are
accessible through <em>either</em> an object instance, or <em>statically</em> through a
property on the the class itself!</p>
<div align="center" class="align-center"><img alt="http://xdissent.com/wp-content/uploads/2010/01/scanners-headexplode.jpg" class="align-center" src="http://xdissent.com/wp-content/uploads/2010/01/scanners-headexplode.jpg" /></div>
<p>Yeah. &quot;<strong>Simple</strong>.&quot;</p>
<p>To be honest, most of the difficulty in understanding descriptors stems
from the fact that (especially in PHP,) classes aren&#8217;t really thought of as
&quot;objects&quot; much. Classes in general are a little bit &quot;quirky&quot; in PHP, being
referenced as a quoted class name string half the time, an unquoted global
class name the other half, and as a special keyword the other-other half!
Only now are the more advanced class related tools even appearing in the PHP
world, and they&#8217;re still not complete (which will really screw us later in this
article). Plus there&#8217;s just not that much information about down and dirty
class-level manipulation for PHP out there. Where the official documentation
is lacking, it&#8217;s only supplemented by helpless user comments flailing wildly
trying to understand the murky examples. It&#8217;s a real shame because ultimately,
we as developers fall victim to the catch 22 of PHP&#8217;s evolution as a language:
Features will be added after widespread adoption of the feature.&quot; Progress
happens very slowly because developers lack the understanding (or perhaps
the vision) to take advantage of some of these features &#8211; much less
successfully lobby for improvements in the language itself. Regardless,
I&#8217;ll admit I never really even thought of classes in such a dynamic way
until I switched to Python. So, if you&#8217;ve never been exposed to Python and
its <em>very</em> object-like class syntax, then it&#8217;s going to be an even longer
road to enlightenment! No worries though, let&#8217;s just break it down slowly
and see what descriptors really look like: Descriptors <em>are</em>&#8230;</p>
<div class="section" id="object-instances">
<h3>object instances&#8230;</h3>
<p>Ok, so that means we&#8217;re dealing with an instance of a class, which will
obviously require a class definition. That&#8217;s a pretty simple concept -
define a class and create an instance of it. Somewhere along the line,
we&#8217;re going to have to define some kind of &quot;descriptor&quot; class, and
instantiate it. No big deal. With that in mind, let&#8217;s move on: Descriptors
are object instances&#8230;</p>
</div>
<div class="section" id="posing-as-dynamic-properties">
<h3>posing as dynamic properties&#8230;</h3>
<p>Dynamic properties are a slightly advanced concept, and usually make use of
the <tt class="docutils literal">__get</tt> <a class="reference external" href="http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members">magic method</a> (and friends), which PHP automatically calls
when you try to access a non-existant property (member variable) on an object
instance. For example, in the following code, <tt class="docutils literal">$obj</tt> will be an instance of
<tt class="docutils literal">TheClass</tt> and <tt class="docutils literal">the_property</tt> will be normal, <em>non-dynamic</em> instance
property:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define the class.</span>
    <span class="k">class</span> <span class="nc">TheClass</span>
    <span class="p">{</span>
        <span class="c">// Declare the property.</span>
        <span class="k">public</span> <span class="nv">$the_property</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c">// Create the object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">TheClass</span><span class="p">();</span>

    <span class="c">// Access the object instance&#39;s property.</span>
    <span class="k">echo</span> <span class="s1">&#39;The property: &#39;</span> <span class="o">.</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">the_property</span><span class="p">;</span>
</pre></div>
<p>The property is accessed as <tt class="docutils literal"><span class="pre">$obj-&gt;the_property</span></tt>. The following call will
issue a <tt class="docutils literal">Notice</tt> level error by default, since we attempt to access
an undeclared property on <tt class="docutils literal">$obj</tt>:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Access a nonexistent property.</span>
    <span class="k">echo</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">bogus_property</span><span class="p">;</span>
</pre></div>
<p>However, if the class defines an instance method named <tt class="docutils literal">__get</tt>, it can
intercept requests for undefined properties, and return a dynamic value.
That means we can calculate a value at runtime for what the world will
think is a normal instance property. The end product looks something like this:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define the class.</span>
    <span class="k">class</span> <span class="nc">DynamicClass</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Returns the value of a dynamic property.</span>
<span class="sd">         *</span>
<span class="sd">         * This method will issue a &#39;Notice&#39; level error if a nonexistent</span>
<span class="sd">         * property is requested.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name The name of the property to get.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__get</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Check the name of the requested property.</span>
            <span class="k">if</span> <span class="p">(</span><span class="nv">$name</span> <span class="o">==</span> <span class="s1">&#39;the_property&#39;</span><span class="p">)</span> <span class="p">{</span>

                <span class="c">// Return the dynamic value for &#39;the_property&#39; property.</span>
                <span class="k">return</span> <span class="nb">time</span><span class="p">();</span>
            <span class="p">}</span>

            <span class="c">// Trigger an error if no property was found with the name.</span>
            <span class="nb">trigger_error</span><span class="p">(</span><span class="nb">sprintf</span><span class="p">(</span>
                <span class="s1">&#39;Undefined property: %s::$%s&#39;</span><span class="p">,</span>
                <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">),</span>
                <span class="nv">$name</span>
            <span class="p">));</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Create the object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">DynamicClass</span><span class="p">();</span>

    <span class="c">// Access the object instance&#39;s property.</span>
    <span class="k">echo</span> <span class="s1">&#39;The property: &#39;</span> <span class="o">.</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">the_property</span><span class="p">;</span>
</pre></div>
<p>Now every time we access the <tt class="docutils literal"><span class="pre">$obj-&gt;the_property</span></tt> property, the <tt class="docutils literal">__get</tt>
method will be evaluated, and &#8211; specifically &#8211; the current time will be
returned.</p>
<p>That&#8217;s really all there is to the concept of dynamic properties. They&#8217;re
incredibly convenient though, and <em>indispensable</em> when you want to define
a clean and easy to understand API or standard interface to some functionality.
There are in fact even more magic methods, allowing you to control property
access in contexts other than &quot;getting.&quot; We&#8217;ll deal with a few of them later.</p>
<p>Let&#8217;s get back to unraveling the mystery of descriptors. We know that they&#8217;re
object instances (duh), and that they <em>themselves</em> somehow pose as dynamic
properties. That means that, similarly to the <tt class="docutils literal">__get</tt> method we&#8217;ve just
seen, descriptors handle access requests for undefined properties.
It&#8217;s not clear how an object instance actually <em>does</em> this amazing feat yet,
but let&#8217;s take it one step at a time: Descriptors are object instances
posing as dynamic properties&#8230;</p>
</div>
<div class="section" id="which-are-defined-on-a-class">
<h3>which are defined on a <em>class</em>&#8230;</h3>
<p>Holy crap, say what? Defined on a <em>class</em>? How do you define a property on
a class? Well, in the biz, we call a property defined on a <em>class</em>, a static
property. &quot;Class members&quot;, &quot;class properties&quot;, &quot;static properties&quot; &#8211; it&#8217;s all
the same. In fact, the PHP documentation can&#8217;t even make up its mind what
to call them. The premise is simple though. Remember that in PHP, classes are
defined globally. It might help to think of the class definition itself as
just a block of sourcecode that creates a single global instance of a &quot;class&quot;
type object the first time it is run. These global &quot;class&quot; object instances
have their own properties and methods, <em>plus</em> they know the how to do the
voodoo (that they do) to create a local instance of the class they represent
(so well). To declare a static class property, you just use the <tt class="docutils literal">static</tt>
keyword in the class definition, and that property will now only be accessible
through the class itself and <em>not</em> through instances. The <cite>scope resolution</cite>
operator can be used to get the static property&#8217;s value:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="k">class</span> <span class="nc">StaticPropertyClass</span>
    <span class="p">{</span>
        <span class="c">// Declare the static property.</span>
        <span class="k">public</span> <span class="k">static</span> <span class="nv">$the_static_property</span><span class="p">;</span>

        <span class="c">// Declare the property.</span>
        <span class="k">public</span> <span class="nv">$the_property</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c">// Create the object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">StaticPropertyClass</span><span class="p">();</span>

    <span class="c">// Access the object instance&#39;s property.</span>
    <span class="k">echo</span> <span class="s1">&#39;The property: &#39;</span> <span class="o">.</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">the_property</span><span class="p">;</span>

    <span class="c">// Access the static class property.</span>
    <span class="k">echo</span> <span class="s1">&#39;The class property: &#39;</span> <span class="o">.</span> <span class="nx">StaticPropertyClass</span><span class="o">::</span><span class="nv">$the_static_property</span><span class="p">;</span>

    <span class="c">// This will produce an error.</span>
    <span class="k">echo</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">the_static_property</span><span class="p">;</span>

    <span class="c">// And so will this.</span>
    <span class="k">echo</span> <span class="nx">StaticPropertyClass</span><span class="o">::</span><span class="nv">$the_property</span><span class="p">;</span>
</pre></div>
<p>As you can see, class properties are completely separate from (and oblivious
to) instance properties. They represent a unique global value, associated
with the theoretical &quot;global instance&quot; of the &quot;class&quot; type object. Got it? Good.
To review, a descriptor is really just an object that happens to be stored
in a class property on some random class. It also will intercept and
specially handle requests for some sort of dynamic property, which we haven&#8217;t
really talked about yet. We do know that the value for the hypothetical
property will be&#8230;</p>
</div>
<div class="section" id="evaluated-at-runtime-by-a-method-on-the-descriptor-object-itself">
<h3>evaluated at runtime by a method on the descriptor object itself&#8230;</h3>
<p>That means that every time we try to get the value of the dynamic property,
the descriptor instance will run an instance method to determine the returned
value. So a descriptor has to define some kind of processing method, which
is loosely equivalent to the <tt class="docutils literal">__get</tt> method we used earlier. The real
difference is that the PHP magic methods only automatically handle access
to dynamic properties on the exact instance on which the property is accessed.
The descriptor differs in that (somehow) it intercepts property access for
a <em>different</em> object, not itself.</p>
<p>Now our picture of a descriptor is complete, even though we don&#8217;t really
know how it&#8217;s going to work or what it&#8217;s for yet. According to what we
just discussed, we&#8217;re simply dealing with an instance of a class, with
a method that will calculate and return the dynamic value of the property
which the descriptor instance represents. And it goes a little something
like this:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define the descriptor class.</span>
    <span class="k">class</span> <span class="nc">DescriptorClass</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Calculates and returns the dynamic value for the property</span>
<span class="sd">         * associated with the descriptor instance.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">getDescriptor</span><span class="p">()</span>
        <span class="p">{</span>
            <span class="c">// Do some special calculations.</span>
            <span class="k">return</span> <span class="nb">time</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Create a descriptor.</span>
    <span class="nv">$the_descriptor</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">DescriptorClass</span><span class="p">();</span>

    <span class="c">// Add the descriptor to the class.</span>
    <span class="nx">StaticPropertyClass</span><span class="o">::</span><span class="nv">$the_static_property</span> <span class="o">=</span> <span class="nv">$the_descriptor</span><span class="p">;</span>
</pre></div>
<p>That&#8217;s it! Now <tt class="docutils literal">$the_descriptor</tt> object fits all of the criteria of a
descriptor so far. It&#8217;s stored in a static class property
(<tt class="docutils literal"><span class="pre">StaticPropertyClass::$the_static_property</span></tt>), it&#8217;s an instance
of a class and it has an instance method called <tt class="docutils literal">getDescriptor</tt> that
will return a dynamic value for some property somewhere. Ah yes &#8211; we have
to figure out how the descriptor relates to <em>the property</em>. Recall that
descriptors intercept requests for dynamic properties&#8230;</p>
</div>
<div class="section" id="that-are-accessible-through-either-an-object-instance">
<h3>that are accessible through <em>either</em> an object instance&#8230;</h3>
<p>Hold it right there! Forget the &quot;either&quot; for right now and let&#8217;s focus on
this part. The dynamic properties we&#8217;re going to be using with descriptors
are accessible through an object instance. So really, when we&#8217;ve got our
descriptor working correctly, we should be able to access a dynamic instance
property just like we did using <tt class="docutils literal">__get</tt> earlier. The important thing to
note is that the <em>name</em> of the static class property in which the descriptor
is stored should be the name of the instance property we use to get the
dynamic value from the descriptor instance. I&#8217;ll say that again &#8211; store
a descriptor instance in a class property, use the name of that class
property to access the descriptor in an instance of that class. For
example, using the descriptor we stored in
<tt class="docutils literal"><span class="pre">StaticPropertyClass::$the_static_property</span></tt>, we would access the
descriptor&#8217;s calculated property value using <tt class="docutils literal"><span class="pre">$obj-&gt;the_static_property</span></tt>:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Create the object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">StaticPropertyClass</span><span class="p">();</span>

    <span class="c">// Access the dynamic property, calculated by the descriptor instance.</span>
    <span class="k">echo</span> <span class="s1">&#39;Current time: &#39;</span> <span class="o">.</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">the_static_property</span><span class="p">;</span>
</pre></div>
<p>Every time we access <tt class="docutils literal"><span class="pre">$obj-&gt;the_static_property</span></tt>, we need
<tt class="docutils literal"><span class="pre">StaticPropertyClass::$the_static_property-&gt;getDescriptor()</span></tt> to run. Now
that we&#8217;re clear, we can actually go about implementing some interfaces and
a class that will take care of the actual property request handling. It&#8217;s
not as hard as it sounds! Let&#8217;s start by defining a <tt class="docutils literal">DescriptorInterface</tt>
interface, which will need to be implemented by each descriptor class we
create.</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// An interface that all descriptors will implement.</span>
    <span class="k">interface</span> <span class="nx">DescriptorInterface</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Returns the value of the descriptor when accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed. &#39;null&#39; will be passed if accessed the</span>
<span class="sd">         *                         descriptor was accessed statically.</span>
<span class="sd">         * @param string $owner    The name of the class which owns the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">getDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$owner</span><span class="p">);</span>
    <span class="p">}</span>
</pre></div>
<p>Notice that we added parameters to the <tt class="docutils literal">getDescriptor</tt> method. These are
the parameters specified by the Python descriptor interface and they&#8217;ll
<em>really</em> come in handy later. For now just understand that the first
parameter is always the object instance whose descriptor property is being
accessed and the second parameter will always be the name of the class on
which the descriptor is defined. For example:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define a descriptor.</span>
    <span class="k">class</span> <span class="nc">ChattyDescriptor</span> <span class="k">implements</span> <span class="nx">DescriptorInterface</span>
    <span class="p">{</span>
        <span class="c">// Calculate the dynamic value.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">getDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$owner</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">return</span> <span class="nb">sprintf</span><span class="p">(</span>
                <span class="s2">&quot;Hey %s, you&#39;re a %s.&quot;</span><span class="p">,</span>
                <span class="nv">$instance</span><span class="o">-&gt;</span><span class="na">name</span><span class="p">,</span>
                <span class="nv">$owner</span>
            <span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Define a simple class.</span>
    <span class="k">class</span> <span class="nc">Dude</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="k">public</span> <span class="k">static</span> <span class="nv">$descriptor</span><span class="p">;</span>

        <span class="c">// Assign the name at creation.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Add the descriptor instance to the class.</span>
    <span class="nx">Dude</span><span class="o">::</span><span class="nv">$descriptor</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ChattyDescriptor</span><span class="p">();</span>

    <span class="c">// Create an object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Dude</span><span class="p">(</span><span class="s1">&#39;Broseph&#39;</span><span class="p">);</span>

    <span class="c">// Access the descriptor.</span>
    <span class="k">echo</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">descriptor</span><span class="p">;</span>
</pre></div>
<p>The previous example will output <tt class="docutils literal">Hey Broseph, You're a Dude.</tt> if
everything goes according to plan &#8211; which it won&#8217;t, until we sprinkle some
magic code dust on the <tt class="docutils literal">Dude</tt> class. What we need <tt class="docutils literal">Dude</tt> to take care
of is the hand-off from the dynamic property request to the descriptor&#8217;s
<tt class="docutils literal">getDescriptor</tt> method. Since we&#8217;re definitely not going to want to add
extra code to <em>every single</em> class we use a descriptor with, let&#8217;s agree
that we&#8217;ll need a single base class from which all descriptor-bearing classes
will be extended. In this class, we want to intercept requests for undefined
instance properties, check for a descriptor with the same name in the static
<em>class</em> properties of the instance&#8217;s class, and then call the class property&#8217;s
<tt class="docutils literal">getDescriptor</tt> method if we do in fact find a descriptor object. Here&#8217;s
one implementation of just such a base class:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define a base class for objects that will use descriptors.</span>
    <span class="k">abstract</span> <span class="k">class</span> <span class="nc">Descriptable</span>
    <span class="p">{</span>
        <span class="c">// Intercepts requests for nonexistent properties.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__get</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Get the name of this class.</span>
            <span class="nv">$class</span> <span class="o">=</span> <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>

            <span class="c">// Get an introspection reflection for the class.</span>
            <span class="nv">$class_ref</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ReflectionClass</span><span class="p">(</span><span class="nv">$class</span><span class="p">);</span>

            <span class="c">// Check for a static class property with the given name.</span>
            <span class="nv">$attr</span> <span class="o">=</span> <span class="nv">$class_ref</span><span class="o">-&gt;</span><span class="na">getStaticPropertyValue</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="k">null</span><span class="p">);</span>

            <span class="c">// If the class property is an object, check for a descriptor.</span>
            <span class="k">if</span> <span class="p">(</span><span class="nb">is_object</span><span class="p">(</span><span class="nv">$attr</span><span class="p">))</span> <span class="p">{</span>

                <span class="c">// Get an introspection reflection for the property.</span>
                <span class="nv">$attr_ref</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ReflectionClass</span><span class="p">(</span><span class="nb">get_class</span><span class="p">(</span><span class="nv">$attr</span><span class="p">));</span>

                <span class="c">// Check to see if the static property is a descriptor.</span>
                <span class="k">if</span> <span class="p">(</span><span class="nv">$attr_ref</span><span class="o">-&gt;</span><span class="na">implementsInterface</span><span class="p">(</span><span class="s1">&#39;DescriptorGet&#39;</span><span class="p">))</span> <span class="p">{</span>

                    <span class="c">// Call the descriptor method and return the value.</span>
                    <span class="k">return</span> <span class="nv">$attr</span><span class="o">-&gt;</span><span class="na">getDescriptor</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="nv">$class</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>

            <span class="c">// Trigger an error if no descriptor was found.</span>
            <span class="nb">trigger_error</span><span class="p">(</span><span class="nb">sprintf</span><span class="p">(</span><span class="s1">&#39;Undefined property: %s::$%s&#39;</span><span class="p">,</span> <span class="nv">$class</span><span class="p">,</span> <span class="nv">$name</span><span class="p">));</span>
        <span class="p">}</span>
    <span class="p">}</span>
</pre></div>
<p>Subclasses of <tt class="docutils literal">Descriptable</tt> will now correctly handle descriptors with no
further fiddling. PHP&#8217;s new <a class="reference external" href="http://www.php.net/manual/en/book.reflection.php">reflection</a> API (speaking of undocumented
features) is used to inspect the subclass and the descriptor instance to
determine whether descriptor handling should take place. Here&#8217;s a final,
working example that will correctly implement a descriptor according to the
Python rules we&#8217;ve been over so far:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define a simple class.</span>
    <span class="k">class</span> <span class="nc">WorkingDude</span> <span class="k">extends</span> <span class="nx">Descriptable</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="k">public</span> <span class="k">static</span> <span class="nv">$descriptor</span><span class="p">;</span>

        <span class="c">// Assign the name at creation.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Add the descriptor instance to the class.</span>
    <span class="nx">WorkingDude</span><span class="o">::</span><span class="nv">$descriptor</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ChattyDescriptor</span><span class="p">();</span>

    <span class="c">// Create an object instance.</span>
    <span class="nv">$obj</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">WorkingDude</span><span class="p">(</span><span class="s1">&#39;Brosephus&#39;</span><span class="p">);</span>

    <span class="c">// Access the descriptor (works!)</span>
    <span class="k">echo</span> <span class="nv">$obj</span><span class="o">-&gt;</span><span class="na">descriptor</span><span class="p">;</span>
</pre></div>
<p>Brilliant! We&#8217;ve made a descriptor! The only thing we need to remember about
using the <tt class="docutils literal">Descriptable</tt> class is that if we override the <tt class="docutils literal">__get</tt> method,
we <em>must</em> call the <tt class="docutils literal">__get</tt> method inherited from <tt class="docutils literal">Descriptable</tt>. <em>When</em>
we call it in the overridden method will essentially effect the resolution
order of dynamic properties, so do tread lightly in these cases.</p>
<p>So far we&#8217;ve built a descriptor class that emulates Python&#8217;s descriptors in
all cases but one. Python descriptor properties may be accessed <strong>either</strong>
through an object instance (as we&#8217;ve just shown)&#8230;</p>
</div>
<div class="section" id="or-statically-through-a-property-on-the-the-class-itself">
<h3>or <em>statically</em> through a property on the the class itself!</h3>
<p>And here&#8217;s where we hit the proverbial brick wall. Basically what we need is
a way to trigger a descriptor&#8217;s dynamic processing when accessing a static
class property. The really confusing part is that generally, the static
property will actually contain the descriptor instance itself! Mind Blow
part II, anyone? So every time we access a static class property that
contains a descriptor instance, we want to receive the dynamic value of
the descriptor, not the descriptor instance itself. If we could get that to
work, it would look like this:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define a simple class.</span>
    <span class="k">class</span> <span class="nc">UnemployedDude</span> <span class="k">extends</span> <span class="nx">Descriptable</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="k">public</span> <span class="k">static</span> <span class="nv">$descriptor</span><span class="p">;</span>

        <span class="c">// Assign the name at creation.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__construct</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">name</span> <span class="o">=</span> <span class="nv">$name</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Add the descriptor instance to the class.</span>
    <span class="nx">UnemployedDude</span><span class="o">::</span><span class="nv">$descriptor</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ChattyDescriptor</span><span class="p">();</span>

    <span class="c">// Access the descriptor on the class (doesn&#39;t work!)</span>
    <span class="k">echo</span> <span class="nx">UnemployedDude</span><span class="o">::</span><span class="nv">$descriptor</span> <span class="o">.</span> <span class="s2">&quot; You don&#39;t even exist, you lazy bum!&quot;</span><span class="p">;</span>
</pre></div>
<p>Unfortunately, PHP has a problem. It provides no <tt class="docutils literal">__get</tt> equivalent magic
method for static access. Try as we might, we&#8217;ll <em>never</em> get a dynamic value
for a class property (defined or otherwise). There has been <a class="reference external" href="http://marc.info/?t=121875368600002&amp;r=1&amp;w=2">great
discussion</a>, a <a class="reference external" href="http://bugs.php.net/bug.php?id=45002">legendary bug ticket</a> and even <a class="reference external" href="http://wiki.php.net/rfc/static-classes#class_model_rules">an RFC</a> dealing with the
addition of a <tt class="docutils literal">__getStatic</tt> magic method to the PHP core, but PHP 5.3
shipped without even a hint of progress in this area. Quel bummer, man! So
all static class properties <em>must</em> be declared in the class definition,
period. In fact, our descriptor implementation subtley <em>relies</em> on this
quirk. When <tt class="docutils literal">__getStatic</tt> is finally available our descriptor class will
require that the class property be undefined in the class definition, and
assigned later. The assignment would take place in the <tt class="docutils literal">__setStatic</tt> magic
method, which would be tasked with keeping track of added descriptors, most
likely in an array keyed off the property name for each descriptor. Yes, it
will be a brave new world for sure! Oh well, it looks like we were just
wasting our time on this descriptor pipe dream.</p>
<p>Not so fast! Don&#8217;t throw your keyboard in the trashcan yet &#8211; there is hope.
First, let&#8217;s examine precisely how big of a deal this one restriction on
our PHP descriptors is. Why would you even want static access to a dynamic
descriptor property? Coincidentally, you <em>probably</em> wouldn&#8217;t
want access to the dynamic value <em>at all</em>! In practice, descriptors rarely
define special handling for the class itself, rather they focus on manipulating
object instances. So the use cases are few in which you will even be dealing
with a descriptor <em>value</em> statically. What you&#8217;ll see far more often is
a descriptor returning its own <em>instance</em> instead of a value when it is
accessed as a static class property. If you think about it, this makes
total sense. How else are you supposed to ever get at the descriptor instance
otherwise? If <tt class="docutils literal"><span class="pre">UnemployedDude::$descriptor</span></tt> returned a <em>value</em>, there
would be no way to get at the descriptor instance at all, since that&#8217;s the
only way we know how to refer to the damn thing. This is just how PHP works
(which we&#8217;re stuck with) and it happens to correlate with the most likely
use case for a descriptor (luckily) so our descriptor class is still very
faithful to the Python equivalent.</p>
<p>One quick thing to note is that the dynamic accessor method required by the
descriptor interface accepts an instance parameter which will contain the
object instance whose descriptor property was requested. In a class descriptor
context, this parameter would always be <tt class="docutils literal">null</tt> since there is no instance
in a static context.</p>
</div>
</div>
<div class="section" id="meet-the-family">
<h2>Meet the Family</h2>
<p>Up to this point, we&#8217;ve ignored a <em>huge</em> detail. In reality, &quot;getting&quot; isn&#8217;t
the only access method supported by Python descriptors. There is also support
for dynamic value &quot;setting&quot; and &quot;deleting.&quot; These actions roughly correspond
to the PHP magic methods <tt class="docutils literal">__set</tt> and <tt class="docutils literal">__unset</tt>, and should be fairly self
explanatory. Descriptors intercept property &quot;setting&quot; and &quot;unsetting&quot; just as
they do for property &quot;getting&quot; currently. To fill out our descriptor
implementation, we should define some new interfaces to define how these new
methods will be called by the descriptable class.</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// The descriptor interface for &quot;set&quot; access.</span>
    <span class="k">interface</span> <span class="nx">DescriptorSet</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Sets the value of the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed.</span>
<span class="sd">         * @param mixed  $value    The value that was given to the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">setDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$value</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c">// The descriptor interface for &quot;unset&quot; access.</span>
    <span class="k">interface</span> <span class="nx">DescriptorUnset</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Unsets the descriptor&#39;s value.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">unsetDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">);</span>
    <span class="p">}</span>
</pre></div>
<p>The <tt class="docutils literal">setDescriptor</tt> method will be called when setting the value of a
descriptor property like <tt class="docutils literal"><span class="pre">$obj-&gt;descriptor</span> = 'new value';</tt> and will receive
the new property value in the <tt class="docutils literal">$value</tt> parameter. Note that the
<tt class="docutils literal">unsetDescriptor</tt> method only receives the object instance as a parameter.
If you&#8217;re wondering what happened to the <tt class="docutils literal">$class</tt> parameter that we used
in <tt class="docutils literal">getDescriptor</tt>, good catch! It turns out, Python descriptors do
not allow static access for &quot;setting&quot; and &quot;deleting (unsetting)&quot; descriptor
properties. The reasoning is simple: if these methods were allowed for
static property access, you could never remove the descriptor instance from
the class. A full restart of the program would be required to empty the
static class property. That just isn&#8217;t practical, so the Python authors left
the feature out completely to prevent confusion. This is an extra bonus for
us, since we can&#8217;t use static class property access <em>at all</em> with descriptors
in PHP. That means we&#8217;re really only missing out on the one single use-case.</p>
<p>There is one other detail to descriptors that&#8217;s specific to PHP. Many PHP
developers use <tt class="docutils literal">isset()</tt> to evaluate whether a property exists and is
valid. Unfortunately <tt class="docutils literal">isset()</tt> will return <tt class="docutils literal">false</tt> for <em>any</em> undeclared
property, even if we&#8217;ve overridden the <tt class="docutils literal">__get</tt> method to return a value.
To accurately simulate a real property, we need to override the magic
<tt class="docutils literal">__isset</tt> method to return <tt class="docutils literal">true</tt> if a property is evaluated dynamically.
With this last piece of the puzzle, we are able to construct a robust
descriptable class, completing our PHP descriptor support:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// The base descriptor interface.</span>
    <span class="k">interface</span> <span class="nx">Descriptor</span>
    <span class="p">{</span>
    <span class="p">}</span>

    <span class="c">// The descriptor interface for &quot;get&quot; access.</span>
    <span class="k">interface</span> <span class="nx">DescriptorGet</span> <span class="k">extends</span> <span class="nx">Descriptor</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Returns the value of the descriptor when accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed. &#39;null&#39; will be passed if accessed the</span>
<span class="sd">         *                         descriptor was accessed statically.</span>
<span class="sd">         * @param string $owner    The name of the class which owns the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">getDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$owner</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c">// The descriptor interface for &quot;set&quot; access.</span>
    <span class="k">interface</span> <span class="nx">DescriptorSet</span> <span class="k">extends</span> <span class="nx">Descriptor</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Sets the value of the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed.</span>
<span class="sd">         * @param mixed  $value    The value that was given to the descriptor.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">setDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$value</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c">// The descriptor interface for &quot;unset&quot; access.</span>
    <span class="k">interface</span> <span class="nx">DescriptorUnset</span> <span class="k">extends</span> <span class="nx">Descriptor</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Unsets the descriptor&#39;s value.</span>
<span class="sd">         *</span>
<span class="sd">         * @param object $instance The object instance on which the descriptor was</span>
<span class="sd">         *                         accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">unsetDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="c">// The base class for all descriptor-bearing subclasses.</span>
    <span class="k">abstract</span> <span class="k">class</span> <span class="nc">Descriptable</span>
    <span class="p">{</span>
        <span class="sd">/**</span>
<span class="sd">         * Finds and returns a descriptor instance for the class.</span>
<span class="sd">         *</span>
<span class="sd">         * This method will return null if either a descriptor was not found in</span>
<span class="sd">         * the class property with the specified name, or if a descriptor was</span>
<span class="sd">         * found but does not implement the requested interface. Passing the</span>
<span class="sd">         * default interface name &#39;Descriptor&#39; will return any type of descriptor</span>
<span class="sd">         * as long as it is stored in the correct class property.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name  The name of the descriptor property being accessed.</span>
<span class="sd">         * @param string $iface The name of the descriptor interface which must</span>
<span class="sd">         *                      be supported by the descriptor instance.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">protected</span> <span class="k">function</span> <span class="nf">_descriptorInstance</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="nv">$iface</span><span class="o">=</span><span class="s1">&#39;Descriptor&#39;</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Get an introspection reflection for the class.</span>
            <span class="nv">$class</span> <span class="o">=</span> <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
            <span class="nv">$class_ref</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ReflectionClass</span><span class="p">(</span><span class="nv">$class</span><span class="p">);</span>

            <span class="c">// Get the static class property with the given name.</span>
            <span class="nv">$attr</span> <span class="o">=</span> <span class="nv">$class_ref</span><span class="o">-&gt;</span><span class="na">getStaticPropertyValue</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="k">null</span><span class="p">);</span>

            <span class="c">// Check to see if the property is a descriptor instance.</span>
            <span class="k">if</span> <span class="p">(</span><span class="nb">is_object</span><span class="p">(</span><span class="nv">$attr</span><span class="p">))</span> <span class="p">{</span>

                <span class="c">// Get an introspection reflection of the property.</span>
                <span class="nv">$attr_ref</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ReflectionClass</span><span class="p">(</span><span class="nb">get_class</span><span class="p">(</span><span class="nv">$attr</span><span class="p">));</span>

                <span class="c">// Check to see if the static property has the right interface.</span>
                <span class="k">if</span> <span class="p">(</span><span class="nv">$attr_ref</span><span class="o">-&gt;</span><span class="na">implementsInterface</span><span class="p">(</span><span class="nv">$iface</span><span class="p">))</span> <span class="p">{</span>

                    <span class="c">// Return the found descriptor.</span>
                    <span class="k">return</span> <span class="nv">$attr</span><span class="p">;</span>
                <span class="p">}</span>
            <span class="p">}</span>
            <span class="c">// Return null since we didn&#39;t find a matching descriptor.</span>
            <span class="k">return</span> <span class="k">null</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="sd">/**</span>
<span class="sd">         * Finds and runs a descriptor method for the class.</span>
<span class="sd">         *</span>
<span class="sd">         * This method will run the specified descriptor method of the descriptor</span>
<span class="sd">         * with the provided name if it exists. The method may be one of &#39;get&#39;,</span>
<span class="sd">         * &#39;set&#39;, or &#39;unset&#39;. Any arguments provided in the &#39;$args&#39; array parameter</span>
<span class="sd">         * will be passed to the descriptor method. This method will return &#39;null&#39;</span>
<span class="sd">         * if no matching descriptor instance was found.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $method The name of the descriptor method to run.</span>
<span class="sd">         * @param string $name   The descriptor property name.</span>
<span class="sd">         * @param array  $args   An array of arguments to pass to the descriptor</span>
<span class="sd">         *                       method or &#39;null&#39;.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">protected</span> <span class="k">function</span> <span class="nf">_descriptorAccess</span><span class="p">(</span><span class="nv">$method</span><span class="p">,</span> <span class="nv">$name</span><span class="p">,</span> <span class="nv">$args</span><span class="o">=</span><span class="k">null</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Initialize descriptor method arguments.</span>
            <span class="k">if</span> <span class="p">(</span><span class="nb">is_null</span><span class="p">(</span><span class="nv">$args</span><span class="p">))</span> <span class="p">{</span>
                <span class="nv">$args</span> <span class="o">=</span> <span class="k">array</span><span class="p">();</span>
            <span class="p">}</span>

            <span class="c">// Get the name of the required descriptor interface.</span>
            <span class="nv">$iface</span> <span class="o">=</span> <span class="s1">&#39;Descriptor&#39;</span> <span class="o">.</span> <span class="nb">ucfirst</span><span class="p">(</span><span class="nv">$method</span><span class="p">);</span>

            <span class="c">// Retrieve the descriptor instance matching the name and interface.</span>
            <span class="nv">$attr</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_descriptorInstance</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="nv">$iface</span><span class="p">);</span>

            <span class="c">// Check for a valid descriptor instance.</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nb">is_null</span><span class="p">(</span><span class="nv">$attr</span><span class="p">))</span> <span class="p">{</span>

                <span class="c">// Call the descriptor instance method with the passed arguments.</span>
                <span class="k">return</span> <span class="nb">call_user_func_array</span><span class="p">(</span>
                    <span class="k">array</span><span class="p">(</span><span class="nv">$attr</span><span class="p">,</span> <span class="nv">$method</span> <span class="o">.</span> <span class="s1">&#39;Descriptor&#39;</span><span class="p">),</span>
                    <span class="nv">$args</span>
                <span class="p">);</span>
            <span class="p">}</span>

            <span class="c">// Trigger an error if the appropriate descriptor wasn&#39;t found.</span>
            <span class="nb">trigger_error</span><span class="p">(</span><span class="nb">sprintf</span><span class="p">(</span><span class="s1">&#39;Undefined property: %s::$%s&#39;</span><span class="p">,</span> <span class="nv">$class</span><span class="p">,</span> <span class="nv">$name</span><span class="p">));</span>
            <span class="k">return</span> <span class="k">null</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="sd">/**</span>
<span class="sd">         * Gets a dynamic instance property&#39;s value.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name The name of the instance property being accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @return mixed</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__get</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$args</span> <span class="o">=</span> <span class="k">array</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="nb">get_class</span><span class="p">(</span><span class="nv">$this</span><span class="p">));</span>
            <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_descriptorAccess</span><span class="p">(</span><span class="s1">&#39;get&#39;</span><span class="p">,</span> <span class="nv">$name</span><span class="p">,</span> <span class="nv">$args</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="sd">/**</span>
<span class="sd">         * Sets a dynamic instance property&#39;s value.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name  The name of the instance property being set.</span>
<span class="sd">         * @param string $value The new value to use for the property.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__set</span><span class="p">(</span><span class="nv">$name</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$args</span> <span class="o">=</span> <span class="k">array</span><span class="p">(</span><span class="nv">$this</span><span class="p">,</span> <span class="nv">$value</span><span class="p">);</span>
            <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_descriptorAccess</span><span class="p">(</span><span class="s1">&#39;set&#39;</span><span class="p">,</span> <span class="nv">$name</span><span class="p">,</span> <span class="nv">$args</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="sd">/**</span>
<span class="sd">         * Unsets a dynamic instance property.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name The name of the instance property being unset.</span>
<span class="sd">         *</span>
<span class="sd">         * @return null</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__unset</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nv">$args</span> <span class="o">=</span> <span class="k">array</span><span class="p">(</span><span class="nv">$this</span><span class="p">);</span>
            <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_descriptorAccess</span><span class="p">(</span><span class="s1">&#39;unset&#39;</span><span class="p">,</span> <span class="nv">$name</span><span class="p">,</span> <span class="nv">$args</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="sd">/**</span>
<span class="sd">         * Returns true if a descriptor instance exists in the named class property.</span>
<span class="sd">         *</span>
<span class="sd">         * @param string $name The name of the instance property being accessed.</span>
<span class="sd">         *</span>
<span class="sd">         * @return boolean</span>
<span class="sd">         */</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">__isset</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Simply test to see if we have any descriptor with that name.</span>
            <span class="k">return</span> <span class="nb">is_null</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_descriptorInstance</span><span class="p">(</span><span class="nv">$name</span><span class="p">));</span>
        <span class="p">}</span>
    <span class="p">}</span>
</pre></div>
</div>
<div class="section" id="the-gotchas">
<h2>The Gotchas</h2>
<p>There are some tiny differences between our PHP descriptors and those in
Python, aside from the static access restriction discussed previously. Python&#8217;s
property resolution automatically searches for a class property if an instance
does not contain property with the requested name. PHP does not do this, and
treats static properties very differently. This is unlikely to become an issue
in practice, and is a very specific edge case. Another similar detail is that
Python will short circuit its property resolution if a property defines a
&quot;setting&quot; access method, always using the descriptor even if the instance
defines it&#8217;s own property with the same name. Descriptors which only handle
&quot;getting&quot; of properties will not be used by default. This is very confusing
and really just an intricacy of Python that doesn&#8217;t relate to PHP since we
don&#8217;t have the concept of an object&#8217;s &quot;data dict.&quot; In all except the wildest
of edge cases, these differences may be ignored.</p>
<p>Another small gotcha can pop up when developers erroneously re-include a
source file containing a class definition. Since descriptor instances must
be assigned to a class property and PHP <a class="reference external" href="http://www.php.net/manual/en/language.oop5.properties.php">doesn&#8217;t allow</a> evaluated variables
as property values in the class definition, we&#8217;re forced to add the descriptor
instance to the class <em>after</em> it has been defined. This isn&#8217;t something that
should be feared and it&#8217;s certainly not &quot;wrong&quot; according to how PHP works,
but it is a little off putting to some developers. Regardless, it&#8217;s important
to <em>not</em> re-include a file if it adds a descriptor to a class. Otherwise, a
new instance of the descriptor may suddenly appear in all of the existing
instances of that class. The fix is simple: use <tt class="docutils literal">require_once</tt> like you
should be doing in the first place when importing class definitions.</p>
</div>
<div class="section" id="the-payoff">
<h2>The Payoff</h2>
<p>At this point you&#8217;re probably very angry (and crosseyed) after having read
this exhausting tome, and yet we still haven&#8217;t explored <em>why</em> descriptors
are useful in the first place. Let&#8217;s go over a few benefits descriptors have
over other types of dynamic properties.</p>
<div class="section" id="easy-class-wide-caching">
<h3>Easy (Class-wide) Caching</h3>
<p>A classic use case for dynamic properties is value caching. If the value
of a property is expensive to calculate, it&#8217;s trivial to set up a dynamic
property that calculates the value once, store it locally in the object
instance and return the calculated value upon subsequent access. The down
side to simple caching (probably using the <tt class="docutils literal">__get</tt> method) is that the
cache is local to the object. That means in naive implementations the
value is calculated <em>and</em> stored each and every time you create an object
instance and try to access the dynamic property. This is unneccessary
when the calculated value will not differ between object instances. Of course
this problem only gets larger the more instances you actually create.</p>
<p>Descriptors open up the possibility of per-class caching, rather than
per-object caching since descriptor instances are defined on a class. Even
when accessed on different object instances, a single descriptor property
instance is handling all of the requests. This allows the descriptor to
be used as a class-wide cache with very little effort. Using a descriptor
in this way can be a lifesaver for intensive operations like database
access:</p>
<div class="highlight"><pre><span class="cp">&lt;?php</span>
    <span class="c">// Define a descriptor to manage retrieving the high score.</span>
    <span class="k">class</span> <span class="nc">HighScoreDescriptor</span>
    <span class="k">implements</span> <span class="nx">DescriptorGet</span><span class="p">,</span> <span class="nx">DescriptorSet</span>
    <span class="p">{</span>
        <span class="k">protected</span> <span class="nv">$_high_score</span><span class="p">;</span>

        <span class="c">// Returns the current high score.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">getDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$owner</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Check to see if we&#39;ve already retreived the high score.</span>
            <span class="k">if</span> <span class="p">(</span><span class="nb">is_null</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_high_score</span><span class="p">))</span> <span class="p">{</span>

                <span class="c">// Fetch and cache the high score from the db.</span>
                <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_high_score</span> <span class="o">=</span> <span class="nx">get_from_db</span><span class="p">(</span><span class="s1">&#39;high_score&#39;</span><span class="p">);</span>
            <span class="p">}</span>

            <span class="c">// Return the cached high score.</span>
            <span class="k">return</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_high_score</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="c">// Sets the current high score.</span>
        <span class="k">public</span> <span class="k">function</span> <span class="nf">setDescriptor</span><span class="p">(</span><span class="nv">$instance</span><span class="p">,</span> <span class="nv">$value</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="c">// Update the cached high score.</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_high_score</span> <span class="o">=</span> <span class="nv">$value</span><span class="p">;</span>

            <span class="c">// Save the new high score to the db.</span>
            <span class="nx">update_db</span><span class="p">(</span><span class="s1">&#39;high_score&#39;</span><span class="p">,</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_high_score</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="c">// Define a scored game class.</span>
    <span class="k">class</span> <span class="nc">ScoredGame</span> <span class="k">extends</span> <span class="nx">Descriptable</span>
    <span class="p">{</span>
        <span class="c">// Define a class property to hold the high score descriptor.</span>
        <span class="k">public</span> <span class="k">static</span> <span class="nv">$high_score</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="c">// Add a high score descriptor to the class.</span>
    <span class="nx">ScoredGame</span><span class="o">::</span><span class="nv">$high_score</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">HighScoreDescriptor</span><span class="p">();</span>

    <span class="c">// Create a game instance.</span>
    <span class="nv">$game</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ScoredGame</span><span class="p">();</span>

    <span class="c">// Retrieve the high score for the game (db queried).</span>
    <span class="k">echo</span> <span class="s1">&#39;High Score: &#39;</span> <span class="o">.</span> <span class="nv">$game</span><span class="o">-&gt;</span><span class="na">high_score</span><span class="p">;</span>

    <span class="c">// Set the high score, cheater.</span>
    <span class="nv">$game</span><span class="o">-&gt;</span><span class="na">high_score</span> <span class="o">=</span> <span class="m">31337</span><span class="p">;</span>

    <span class="c">// Retreive the high score again (db *not* queried).</span>
    <span class="k">echo</span> <span class="s1">&#39;New High Score: &#39;</span> <span class="o">.</span> <span class="nv">$game</span><span class="o">-&gt;</span><span class="na">high_score</span><span class="p">;</span>

    <span class="c">// Create another game instance.</span>
    <span class="nv">$another_game</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ScoredGame</span><span class="p">();</span>

    <span class="c">// Retrieve the high score for the new game (db *still* not queried).</span>
    <span class="k">echo</span> <span class="s1">&#39;Same High Score: &#39;</span> <span class="o">.</span> <span class="nv">$another_game</span><span class="o">-&gt;</span><span class="na">high_score</span><span class="p">;</span>
</pre></div>
</div>
<div class="section" id="memory-footprint">
<h3>Memory Footprint</h3>
<p>It&#8217;s obvious that caching values with descriptors saves you from executing
expensive operations multiple times, but what about the amount of memory
used? When you cache a variable locally per-instance, you&#8217;re storing that
information once for each instance that requests it. Descriptors use <em>far</em>
less memory in this case by only storing one copy. This idea can be extended
into realms other than simple caching, and will always reap the rewards of
leaner memory usage.</p>
</div>
<div class="section" id="cleaner-than-the-alternatives">
<h3>Cleaner Than the Alternatives</h3>
<p>Implementing a dynamic property with the <tt class="docutils literal">__get</tt> magic method requires
checking the name of the requested property to determine whether or not
it should be dynamically handled. Once that is determined, the <tt class="docutils literal">__get</tt>
method must then figure out what to actually do to calculate the dynamic
value. Innumerable approaches to this problem exist in the wild, and that&#8217;s
a problem in itself. There exists no standard way of determining what
should be called, when, and in which context with traditional dynamic
variables. Descriptors provide a standardized interface to these concepts,
and don&#8217;t require hacky switch statements with string checking, or a gazillion
<tt class="docutils literal">setSomething</tt> and <tt class="docutils literal">getSomething</tt> stop-gap methods. Descriptions are
cleaner and easier.</p>
</div>
<div class="section" id="true-object-oriented-design">
<h3>True Object Oriented Design</h3>
<p>Whether or not you&#8217;re an OOP lover (or even a hater) doesn&#8217;t matter. You have
to agree that this confusing middle ground in which PHP has been living
sucks. Descriptors promote the concept of PHP classes as objects themselves,
which is what they really are. This is a good move for the language if it
is even going to try to compete with the Pythons and Rubys of tomorrow. If
functionality is class-wide, move it up to the class logic level where it
belongs!</p>
</div>
</div>
<div class="section" id="conclusion">
<h2>Conclusion</h2>
<p>Descriptors are fun, they&#8217;re cool, and they&#8217;re just an all around good tool
to have in your toolbox. They&#8217;re the ideal solution to some very complex,
real world problems that have plagued developers for years. I long for the
day when PHP releases support for dynamic class properties as well so we
can get our hands on a drop-in replacement for Python&#8217;s descriptors. Until
then, the descriptor interfaces and descriptable object class we&#8217;ve just
designed will fit the bill just fine.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2010/01/15/mimicking-python-descriptors-in-php/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Leverage Twitter&#8217;s Distraction Value to Stay Focused</title>
		<link>http://xdissent.com/2009/07/03/leverage-twitters-distraction-value-to-stay-focused/</link>
		<comments>http://xdissent.com/2009/07/03/leverage-twitters-distraction-value-to-stay-focused/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 23:14:50 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[Productivity]]></category>
		<category><![CDATA[GTD]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=56</guid>
		<description><![CDATA[

Twitter by nature is a stream of distractions. I personally never keep Twitter open and visible while I&#8217;m working because I know I&#8217;ll be too easily derailed from whatever I&#8217;m doing. If Life Hacker reported that a single email arriving in your inbox can cost you over a minute of mental recovery time, Twitter&#8217;s rapid-fire [...]]]></description>
			<content:encoded><![CDATA[

<p><a class="reference external" href="http://twitter.com">Twitter</a> by nature is a stream of distractions. I personally never keep Twitter open and visible while I&#8217;m working because I know I&#8217;ll be too easily derailed from whatever I&#8217;m doing. If <a class="reference external" href="http://lifehacker.com">Life Hacker</a> <a class="reference external" href="http://lifehacker.com/5048463/single-email-interruption-recovery-time-over-a-minute">reported</a> that a single email arriving in your inbox can cost you over a minute of mental recovery time, Twitter&#8217;s rapid-fire updates could prove to be literally stupefying. <span id="more-56"></span> With that in mind, it&#8217;s probably a good idea to set aside a particular time of day to catch up on your tweets to prevent wasting too much time.</p>
<p>Once you&#8217;re committed to the idea that Twitter is a serious time waster, you can then use it to save a few more <a class="reference external" href="http://www.preciousmoments.com/">precious moments</a> of your day that would otherwise be lost to internet distractions. For example, instead of subscribing to other distracting feeds and sites in your normal feed reader, downgrade them to twitter feeds and conglomerate your slacking. Most such sites mirror their feed on Twitter anyway, so catch up on all your time-wasters all at once &#8211; when you have the time to waste. Your reader can then be used for more serious items that might actually require your attention. Plus you&#8217;ll have the added bonus of <em>missing</em> a few posts during the day due to the sheer traffic on Twitter, which means less time wasted period. And really, you wouldn&#8217;t really <em>miss</em> another lolcat, would you?</p>
<p>Want to try it out? Follow <a class="reference external" href="http://godbitesman.com">&#64;godbitesman</a>, <a class="reference external" href="http://thisisphotobomb.com">&#64;thisisphotobomb</a>, <a class="reference external" href="http://itemnotasdescribed.com">&#64;notasdescribed</a>, and of course, <a class="reference external" href="http://failblog.org">&#64;failblog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2009/07/03/leverage-twitters-distraction-value-to-stay-focused/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>uTidyLib Fix</title>
		<link>http://xdissent.com/2009/03/15/utidylib-fix/</link>
		<comments>http://xdissent.com/2009/03/15/utidylib-fix/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 19:41:41 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[OSX]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=35</guid>
		<description><![CDATA[


uTidyLib is a Python wrapper for the HTML
Tidy Library. It&#8217;s a pretty handy library and is dead
simple to use, but unfortunately it does not compile on Leopard out of the
box. I wrote a quick patch to fix it, and will maintain a vendor branch on GitHub since
development seems to have been abandoned years ago.

The other [...]]]></description>
			<content:encoded><![CDATA[


<p><a class="reference external" href="http://utidylib.berlios.de/">uTidyLib</a> is a Python wrapper for the <a class="reference external" href="http://tidy.sf.net/">HTML
Tidy Library</a>. It&#8217;s a pretty handy library and is dead
simple to use, but unfortunately it does not compile on Leopard out of the
box. I wrote a quick patch to fix it, and will maintain a vendor branch on <a class="reference external" href="http://github.com/xdissent/utidylib/">GitHub</a> since
development seems to have been abandoned years ago.</p>
<span id="more-35"></span>
<p>The other day I wrote a tiny Django middleware that alerts me if a response
contains markup errors (debug only of course). uTidyLib looked promising, but
I couldn&#8217;t get pip to successfully install the damn thing. My deployment
environment needs to be able to use pip so I had to patch <tt class="docutils literal">setup.py</tt> to be
setuptools friendly.</p>
<div class="highlight"><pre><span class="gp">xdissent@stewart:~$</span> mkvirtualenv tidy_fix
<span class="go">New python executable in tidy_fix/bin/python</span>
<span class="go">Installing setuptools............done.</span>
<span class="gp">(tidy_fix)xdissent@stewart:~$</span> easy_install pip
<span class="go">Searching for pip</span>
<span class="go">Reading http://pypi.python.org/simple/pip/</span>
<span class="go">[..]</span>
<span class="go">Finished processing dependencies for pip</span>
<span class="gp">(tidy_fix)xdissent@stewart:~$</span> pip install http://download.berlios.de/utidylib/uTidylib-0.2.zip
<span class="go">Downloading/unpacking http://download.berlios.de/utidylib/uTidylib-0.2.zip</span>
<span class="go">  Downloading uTidylib-0.2.zip</span>
<span class="go">  Running setup.py egg_info for package from http://download.berlios.de/utidylib/uTidylib-0.2.zip</span>
<span class="go">Installing collected packages: uTidylib</span>
<span class="go">  Running setup.py install for uTidylib</span>
<span class="go">    usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]</span>
<span class="go">       or: -c --help [cmd1 cmd2 ...]</span>
<span class="go">       or: -c --help-commands</span>
<span class="go">       or: -c cmd --help</span>

<span class="go">    error: option --single-version-externally-managed not recognized</span>
<span class="go">    Complete output from command /Users/xdissent/.virtualenvs/tidy_fix/bin/python -c &quot;import setuptools; __file__=&#39;/var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-1c9Slw-build/setup.py&#39;; execfile(&#39;/var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-1c9Slw-build/setup.py&#39;)&quot; install --single-version-externally-managed --record /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-SEIOXm-record/install-record.txt --install-headers /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/lib/include:</span>
<span class="go">    usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]</span>

<span class="go">   or: -c --help [cmd1 cmd2 ...]</span>

<span class="go">   or: -c --help-commands</span>

<span class="go">   or: -c cmd --help</span>



<span class="go">error: option --single-version-externally-managed not recognized</span>

<span class="go">----------------------------------------</span>
<span class="go">Command /Users/xdissent/.virtualenvs/tidy_fix/bin/python -c &quot;import setuptools; __file__=&#39;/var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-1c9Slw-build/setup.py&#39;; execfile(&#39;/var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-1c9Slw-build/setup.py&#39;)&quot; install --single-version-externally-managed --record /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-SEIOXm-record/install-record.txt --install-headers /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/lib/include failed with error code 1</span>
<span class="go">Storing complete log in ./pip-log.txt</span>
</pre></div>
<p>The message <tt class="docutils literal">error: option <span class="pre">--single-version-externally-managed</span> not recognized</tt>
means <tt class="docutils literal">setup.py</tt> is subclassing <tt class="docutils literal">distutils.command.install.install</tt>, which
sucks because we want to use <tt class="docutils literal">setuptools</tt>. The fix is easy though: just
change the import statement in <tt class="docutils literal">setup.py</tt> to
<tt class="docutils literal">from setuptools.command.install import install</tt>. I got it all patched up and
into my vendor SVN repository, but ran across another problem when trying to
use pip.</p>
<div class="highlight"><pre><span class="gp">(tidy_fix)xdissent@stewart:~$</span> pip install http://code.hartzogcreative.com/svn/vendor/utidylib/current
<span class="go">Downloading/unpacking http://code.hartzogcreative.com/svn/vendor/utidylib/current</span>
<span class="go">  Downloading current</span>
<span class="go">  Checking out svn repository http://code.hartzogcreative.com/svn/vendor/utidylib/current to /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/pip-mOglX5-build</span>
<span class="go">  Running setup.py egg_info for package from http://code.hartzogcreative.com/svn/vendor/utidylib/current</span>
<span class="go">Installing collected packages: uTidylib</span>
<span class="go">  Running setup.py install for uTidylib</span>
<span class="go">    *** This library requires that you have two libraries ***</span>
<span class="go">    ***           installed: ctypes and libtidy.          ***</span>
<span class="go">    ***   Please make sure they are installed correctly   ***</span>
<span class="go">    ***              before reporting a bug.              ***</span>
<span class="go">    *** See:                                              ***</span>
<span class="go">    ***  http://starship.python.net/crew/theller/ctypes/  ***</span>
<span class="go">    ***         and http://tidy.sourceforge.net           ***</span>
<span class="go">    *** (or consult your vendor documentation for binary  ***</span>
<span class="go">    ***                    packages.)                     ***</span>
<span class="go">Successfully installed uTidylib</span>
</pre></div>
<p>Things look normal here, but uTidyLib thinks differently.</p>
<div class="highlight"><pre><span class="go">Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)</span>
<span class="go">[GCC 4.0.1 (Apple Inc. build 5465)] on darwin</span>
<span class="go">Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">tidy</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
  File <span class="nb">&quot;/Users/xdissent/.virtualenvs/tidy_fix/lib/python2.5/site-packages/tidy/__init__.py&quot;</span>, line <span class="m">43</span>, in <span class="n-Identifier">&lt;module&gt;</span>
    <span class="kn">from</span> <span class="nn">tidy.lib</span> <span class="kn">import</span> <span class="n">parse</span><span class="p">,</span> <span class="n">parseString</span>
  File <span class="nb">&quot;/Users/xdissent/.virtualenvs/tidy_fix/lib/python2.5/site-packages/tidy/lib.py&quot;</span>, line <span class="m">33</span>, in <span class="n-Identifier">&lt;module&gt;</span>
    <span class="k">raise</span> <span class="ne">OSError</span><span class="p">(</span><span class="s">&quot;Couldn&#39;t find libtidy, please make sure it is installed.&quot;</span><span class="p">)</span>
<span class="nc">OSError</span>: <span class="n-Identifier">Couldn&#39;t find libtidy, please make sure it is installed.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="o">^</span><span class="n">D</span>
</pre></div>
<p>uTidyLib looks for libtidy in a few predefined locations, and Leopard&#8217;s
libtidy is <em>not</em> in one of those places. The author doesn&#8217;t take into
consideration the possibility of a library having the extension <tt class="docutils literal">dylib</tt>
so I patched my vendor repository to correctly find libtidy. The source
is available at
<a class="reference external" href="http://github.com/xdissent/utidylib/">http://github.com/xdissent/utidylib/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2009/03/15/utidylib-fix/feed/rss2/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>TextMate reStructuredText Bundle</title>
		<link>http://xdissent.com/2009/02/28/textmate-restructuredtext-bundle/</link>
		<comments>http://xdissent.com/2009/02/28/textmate-restructuredtext-bundle/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 05:43:51 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[reStructuredText]]></category>
		<category><![CDATA[TextMate]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=90</guid>
		<description><![CDATA[TextMate is great for general editing of most text formats. By default,
reStructuredText is not one
of them. This document describes how to fix TextMate so that it is a better
fit for the tools I work with. We want reStructuredText rendered previews
and HTML export functions in TextMate.

Update Monday July 6, 2009: TextMate&#8217;s bundle repository has moved. This
article [...]]]></description>
			<content:encoded><![CDATA[<p>TextMate is great for general editing of most text formats. By default,
<a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> is not one
of them. This document describes how to fix TextMate so that it is a better
fit for the tools I work with. We want reStructuredText rendered previews
and HTML export functions in TextMate.</p>
<span id="more-90"></span>
<p><strong>Update</strong> Monday July 6, 2009: TextMate&#8217;s bundle repository has moved. This
article has been updated to reflect this change.</p>
<p>Requires:
<a class="reference external" href="http://subversion.tigris.org/">Subversion</a>
<a class="reference external" href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>
<a class="reference external" href="http://www.doughellmann.com/projects/virtualenvwrapper/">virtualenvwrapper</a>
<a class="reference external" href="http://macromates.com/">TextMate</a></p>
<div class="section" id="create-a-virtualenv-for-textmate">
<h2>Create a virtualenv for TextMate</h2>
<p>We&#8217;re gonna need to install a few Python packages in order to make this work.
That means it&#8217;s time to fire up virtualenv and make an isolated Python
environment for our fix.</p>
<div class="highlight"><pre><span class="gp">stewart:~ xdissent$</span> mkvirtualenv TextMate
<span class="go">New python executable in TextMate/bin/python</span>
<span class="go">Installing setuptools............done.</span>
</pre></div>
</div>
<div class="section" id="install-pip">
<h2>Install pip</h2>
<p>Virtualenv&#8217;s come pre-loaded with <tt class="docutils literal">easy_install</tt>, but we&#8217;re going to be
changing a couple of files in some packages so we should use <a class="reference external" href="http://pypi.python.org/pypi/pip">pip</a> to make that easier on ourselves.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> easy_install pip
<span class="go">Searching for pip</span>
<span class="go">[...]</span>
<span class="go">Installed /Users/xdissent/.virtualenvs/TextMate/lib/python2.5/site-packages/pip-0.3.1-py2.5.egg</span>
<span class="go">Processing dependencies for pip</span>
<span class="go">Finished processing dependencies for pip</span>
</pre></div>
</div>
<div class="section" id="install-docutils">
<h2>Install Docutils</h2>
<p><a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> is the package that provides
the reStructuredText parsers, so we&#8217;ll definitely be needing <em>that</em>.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> pip install docutils
<span class="go">Downloading/unpacking docutils</span>
<span class="go">  Downloading docutils-0.5.tar.gz (1.3Mb): 1.3Mb downloaded</span>
<span class="go">[...]</span>
<span class="go">Successfully installed docutils</span>
</pre></div>
</div>
<div class="section" id="install-restructuredtext-textmate-bundle">
<h2>Install reStructuredText TextMate Bundle</h2>
<p>TextMate has a bundle repository at
<tt class="docutils literal"><span class="pre">http://svn.textmate.org/trunk/Bundles</span></tt> with a reStructuredText
bundle already built. We need to download that to a place where TextMate will
actually find the bundle and load it. Typically, thats
<tt class="docutils literal">~/Library/Application Support/TextMate/Bundles</tt>.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> mkdir -p ~/Library/Application<span class="se">\ </span>Support/TextMate/Bundles
<span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">cd</span> ~/Library/Application<span class="se">\ </span>Support/TextMate/Bundles
<span class="gp">(TextMate)stewart:Bundles xdissent$</span> svn co http://svn.textmate.org/trunk/Bundles/reStructuredText.tmbundle
<span class="go">A    reStructuredText.tmbundle/Commands</span>
<span class="go">[...]</span>
<span class="go">A    reStructuredText.tmbundle/Syntaxes/reStructuredText.plist</span>
<span class="go">Checked out revision 10740.</span>
</pre></div>
</div>
<div class="section" id="make-restructuredtext-bundle-use-virtualenv">
<h2>Make reStructuredText Bundle use virtualenv</h2>
<p>Now that we have the bundle, we need to let it know that it needs to be
called from inside our virtualenv. The Preview command uses <tt class="docutils literal">rst2html.py</tt>
to generate the preview, and luckily provides a way to customize the path
to <tt class="docutils literal">rst2html.py</tt>. All we need to do is define <tt class="docutils literal">TM_RST2HTML</tt> variable
with the correct path in our <tt class="docutils literal">.bash_profile</tt> and TextMate will find the
right one.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">echo export </span><span class="nv">TM_RST2HTML</span><span class="o">=</span><span class="sb">`</span>which rst2html.py<span class="sb">`</span> &gt;&gt; ~/.bash_profile
<span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">source</span> ~/.bash_profile
</pre></div>
</div>
<div class="section" id="reload-textmate-bundles">
<h2>Reload TextMate Bundles</h2>
<p>If you&#8217;re running TextMate at this point, you can either use the &quot;Bundles&quot;
menu or the following command to reload the bundles and install our new
reStructuredText bundle.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> osascript -e <span class="s1">&#39;tell app &quot;TextMate&quot; to reload bundles&#39;</span>
</pre></div>
</div>
<div class="section" id="bask-in-the-glory">
<h2>Bask in the glory</h2>
<p>We&#8217;re done. Now we can preview or export reStructuredText easily. Open a
reStructuredText file and go wild. It&#8217;s incredibly convenient to preview
documents as you go, and saving them to HTML makes it simple to blog from
TextMate.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> mate ~/Documents/TextMate<span class="se">\ </span>Fixes.rst
</pre></div>
</div>
<div class="section" id="colour-my-world">
<h2>Colour My World</h2>
<p>If you&#8217;re like me, you tend to include source code or console sessions in
your articles. <a class="reference external" href="http://pygments.org/">Pygments</a> is a Python package that
can add syntax highlighting to these snippets, which comes in handy for
previewing in TextMate. Installation is slightly more advanced, but well
worth setting up.</p>
</div>
<div class="section" id="install-mercurial">
<h2>Install Mercurial</h2>
<p>We want to hack on our Pygments package, so we&#8217;re going to want to install
it in editable mode. Plus, the latest stable release doesn&#8217;t have the
<tt class="docutils literal">BashSessionLexer</tt> that I use quite a bit. Pygments uses <a class="reference external" href="http://www.selenic.com/mercurial/">Mercurial</a> for source control, but I don&#8217;t have
a system-wide copy of <tt class="docutils literal">hg</tt>, so I needed to grab one real fast.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> pip install mercurial
<span class="go">Downloading/unpacking mercurial</span>
<span class="go">  Downloading mercurial-1.1.2.tar.gz (952Kb): 952Kb downloaded</span>
<span class="go">[...]</span>
<span class="go">Successfully installed mercurial</span>
</pre></div>
</div>
<div class="section" id="enable-the-fetch-command">
<h2>Enable the <tt class="docutils literal">fetch</tt> command</h2>
<p>When pip installs an editable package from a Mercurial repository, it uses
the <tt class="docutils literal">fetch</tt> command with <tt class="docutils literal">hg</tt>. We need to enable it in our <tt class="docutils literal"><span class="pre">~/.hgrc</span></tt>
file because it&#8217;s disabled by default.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> cat &gt;&gt; ~/.hgrc <span class="s">&lt;&lt;EOF</span>
<span class="gp">&gt;</span><span class="s"> [extensions]</span>
<span class="gp">&gt;</span><span class="s"> fetch =</span>
<span class="gp">&gt;</span><span class="s"> EOF</span>
</pre></div>
</div>
<div class="section" id="get-pygments">
<h2>Get Pygments</h2>
<p>Now we can install Pygments from Mercurial. Pip will download the source and
unpack it into <tt class="docutils literal">$VIRTUAL_ENV/src</tt> before finally creating an <tt class="docutils literal"><span class="pre">.egg-link</span></tt>
file to point our interpreter to the source code.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> pip install -e hg+http://dev.pocoo.org/hg/pygments-main@799#egg<span class="o">=</span>Pygments
<span class="go">Checking out Pygments from hg+http://dev.pocoo.org/hg/pygments-main@799#egg=Pygments checkout from hg+http://dev.pocoo.org/hg/pygments-main@799#egg=Pygments</span>
<span class="go">[...]</span>
<span class="go">    Installed /Users/xdissent/.virtualenvs/TextMate/src/pygments</span>
<span class="go">Successfully installed Pygments</span>
</pre></div>
</div>
<div class="section" id="install-the-restructuredtext-sourcecode-directive">
<h2>Install the reStructuredText <tt class="docutils literal">sourcecode</tt> directive</h2>
<p>Activating syntax highlighting in a document requires the <tt class="docutils literal">sourcecode</tt>
directive which highlights the following block of code. We can switch out
different Pygments lexers using an option after the directive:</p>
<pre class="literal-block">
.. sourcecode:: python

    from hartzog import VERSION
    print 'Running Hartzog %%s' %% VERSION
</pre>
<p>The rendered version looks something like this:</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">hartzog</span> <span class="kn">import</span> <span class="n">VERSION</span>
<span class="k">print</span> <span class="s">&#39;Running Hartzog </span><span class="si">%%s</span><span class="s">&#39;</span> <span class="o">%%</span> <span class="n">VERSION</span>
</pre></div>
<p>The <tt class="docutils literal">sourcecode</tt> directive isn&#8217;t installed automatically, so we&#8217;ll need to
add it ourselves. Directives are simply python functions that must be
registered with docutils before any parsing is done. That means we can&#8217;t use
<tt class="docutils literal">rst2html.py</tt> with highlighting yet because the directive won&#8217;t be loaded.
Pygments does come with the directive already in its source tree, but we&#8217;re
going to have to let virtualenv know where it is, and then modify <tt class="docutils literal">rst2html.py</tt>
to register the directive before it begins parsing.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> add2virtualenv <span class="nv">$VIRTUAL_ENV</span>/src/pygments/external
<span class="gp">(TextMate)stewart:~ xdissent$</span> sed -i <span class="s1">&#39;&#39;</span> <span class="s1">&#39;/^publish_cmdline/i\</span>
<span class="gp">&gt;</span><span class="s1"> __import__(&quot;rst-directive&quot;)</span>
<span class="gp">&gt;</span><span class="s1"> &#39;</span> <span class="sb">`</span>which rst2html.py<span class="sb">`</span>
</pre></div>
</div>
<div class="section" id="colorize-the-preview-command">
<h2>Colorize the Preview command</h2>
<p>What good is all this work if we can&#8217;t see the damn colors? As it stands now,
pygments is marking up our code to be colorized, but the CSS to actually make
the colors show up isn&#8217;t being loaded into our preview window. We have to
enhance the Preview command in the reStructuredText bundle to include Pygments
stylesheets. You can control which Pygments theme will be used by defining
a <tt class="docutils literal">TM_PYGMENTIZE_STYLE</tt> environment variable. I&#8217;ve created a patch that we
can apply to update our bundle.</p>
<div class="highlight"><pre><span class="gh">Index: Commands/Preview.plist</span>
<span class="gh">===================================================================</span>
<span class="gd">--- Commands/Preview.plist  (revision 10740)</span>
<span class="gi">+++ Commands/Preview.plist  (working copy)</span>
<span class="gu">@@ -25,6 +25,13 @@</span>
            border: 1px #888 solid;
            padding: 0 1em;
    }&#39; &amp;gt; $css
<span class="gi">+    if [[ -f &quot;$TM_PYGMENTIZE&quot; ]]</span>
<span class="gi">+    then</span>
<span class="gi">+        if [[ &quot;$TM_PYGMENTIZE_STYLE&quot; = &quot;&quot; ]]</span>
<span class="gi">+            then TM_PYGMENTIZE_STYLE=default</span>
<span class="gi">+        fi</span>
<span class="gi">+        $TM_PYGMENTIZE -S $TM_PYGMENTIZE_STYLE -f html &amp;gt;&amp;gt; $css</span>
<span class="gi">+    fi</span>
    stylesheet=$css
    tmpCreated=&quot;yes&quot;
 fi
</pre></div>
<p>We want to apply the patch into the root of the bundle with <tt class="docutils literal">patch</tt>.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> patch -d ~/Library/Application<span class="se">\ </span>Support/TextMate/Bundles/reStructuredText.tmbundle -p0 -i rst_bundle.diff
<span class="go">patching file Commands/Preview.plist</span>
</pre></div>
</div>
<div class="section" id="tell-textmate-how-to-use-pygmentize">
<h2>Tell TextMate how to use <tt class="docutils literal">pygmentize</tt></h2>
<p>The patch for the Preview command requires an environment variable called
<tt class="docutils literal">TM_PYGMENTIZE</tt> that contains the path to the <tt class="docutils literal">pygmentize</tt> script. We
need to add that to our <tt class="docutils literal">.bash_profile</tt> along with any custom style we want
to use for highlighting.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">echo export </span><span class="nv">TM_PYGMENTIZE</span><span class="o">=</span><span class="nv">$VIRTUAL_ENV</span>/bin/pygmentize &gt;&gt; ~/.bash_profile
<span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">echo export </span><span class="nv">TM_PYGMENTIZE_STYLE</span><span class="o">=</span>fruity &gt;&gt; ~/.bash_profile
<span class="gp">(TextMate)stewart:~ xdissent$</span> <span class="nb">source</span> ~/.bash_profile
</pre></div>
</div>
<div class="section" id="inform-textmate-of-the-updated-preview-command">
<h2>Inform TextMate of the updated Preview command</h2>
<p>Just like before, we want to nudge TextMate so we can check out the new
preview command without restarting.</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> osascript -e <span class="s1">&#39;tell app &quot;TextMate&quot; to reload bundles&#39;</span>
</pre></div>
</div>
<div class="section" id="patch-pygments-for-virtualenv">
<h2>Patch Pygments for virtualenv</h2>
<p>Everything should be working perfectly now in full color, but I went one step
further in my setup to tweak the <tt class="docutils literal">BashSessionLexer</tt> in Pygments. Because I
use virtualenv all the time, my bash prompt usually has a virtual env name
at the beginning, surrounded by parentheses. If I were to use the <tt class="docutils literal">console</tt>
option for <tt class="docutils literal">sourcecode</tt> with a virtualenv active in the session, the lexer
wouldn&#8217;t recognize my prompt and it wouldn&#8217;t get highlighted. I put together
a quick patch for Pygments that correctly highlights virtualenvwrapper style
prompts.</p>
<div class="highlight"><pre><span class="gh">diff -r 9fe544c7818b pygments/lexers/other.py</span>
<span class="gd">--- a/pygments/lexers/other.py      Sat Feb 14 13:27:41 2009 +0100</span>
<span class="gi">+++ b/pygments/lexers/other.py      Sat Feb 28 22:33:39 2009 -0600</span>
<span class="gu">@@ -416,7 +416,7 @@</span>

         for match in line_re.finditer(text):
             line = match.group()
<span class="gd">-            m = re.match(r&#39;^((?:|sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)?|\[\S+[@:]&#39;</span>
<span class="gi">+            m = re.match(r&#39;^((?:\([A-Za-z_0-9-]+\))?(?:|sh\S*?|\w+\S+[@:]\S+(?:\s+\S+)?|\[\S+[@:]&#39;</span>
                          r&#39;[^\n]+\].+)[$#%%])(.*\n?)&#39;, line)
             if m:
                 # To support output lexers (say diff output), the output
</pre></div>
<p>Mercurial patches are weird, so be sure to use the <tt class="docutils literal"><span class="pre">-p1</span></tt> option when applying:</p>
<div class="highlight"><pre><span class="gp">(TextMate)stewart:~ xdissent$</span> patch -d <span class="nv">$VIRTUAL_ENV</span>/src/pygments -p1 -i pygments.diff
<span class="go">patching file pygments/lexers/other.py</span>
</pre></div>
</div>
<div class="section" id="chump-and-a-hoagie">
<h2>Chump and a Hoagie</h2>
<p>That&#8217;s it. Go <a class="reference external" href="http://www.youtube.com/watch?v=4UW2jW1-avA">buck wild</a> on
some reStructuredText in TextMate dawg. You&#8217;ve earned it.</p>
</div>]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2009/02/28/textmate-restructuredtext-bundle/feed/rss2/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Safari 4 Beta and Coda Tabs Joy</title>
		<link>http://xdissent.com/2009/02/28/safari-4-beta-and-coda-tabs-joy/</link>
		<comments>http://xdissent.com/2009/02/28/safari-4-beta-and-coda-tabs-joy/#comments</comments>
		<pubDate>Sat, 28 Feb 2009 18:32:50 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[Productivity]]></category>
		<category><![CDATA[Coda]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[Safari]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=26</guid>
		<description><![CDATA[


So the Safari beta 4 has landed and opinions are all over the place
about the new features. The most consistent target for criticism has
been the changes to the tab interface. Although the differences were a
little disconcerting at first, I&#8217;ve come to love the new tabs and I even
took a cue from Safari and decided to [...]]]></description>
			<content:encoded><![CDATA[


<p>So the <a class="reference external" href="http://www.apple.com/safari/">Safari</a> beta 4 has <a class="reference external" href="http://www.apple.com/safari/download/">landed</a> and opinions are all <strong>over</strong> the place
about the new features. The most consistent target for criticism has
been the changes to the tab interface. Although the differences were a
little disconcerting at first, I&#8217;ve come to love the new tabs and I even
took a cue from Safari and decided to improve one of my most precious
tools: <a class="reference external" href="http://panic.com/">Panic</a>&#8217;s <a class="reference external" href="http://panic.com/coda/">Coda</a>.</p>
<span id="more-26"></span>
<div class="section" id="beta-blues">
<h2>Beta Blues</h2>
<p>I&#8217;ve been kind of bummed reading all the negative responses to Safari&#8217;s
update because I&#8217;m so impressed by the damn thing. It seems like most of
the gripers are claiming Apple ripped off <a class="reference external" href="http://google.com/chrome/">Chrome</a>&#8217;s &quot;Tabs-on-Top&quot; layout
and &quot;Top Sites&quot; feature or that Safari 4 isn&#8217;t as many times faster than
every competitor as Apple claims. So&#8230; when Apple notices good design
they&#8217;re not supposed to act on improving their product? Should Apple have
included tabs <em>at all</em> since they certainly were not the first to develop
the idea?. Nevermind the fact that Chrome wouldn&#8217;t even <strong>exist</strong> if
Apple hadn&#8217;t shared WebKit with the world, since Chrome uses it exclusively
for rendering. So what&#8217;s the problem with a few &quot;good as new&quot; bad-ass
features, dudes? And if the absence of a handful of outdated Safari 3
behaviors is driving you nuts, you can <a class="reference external" href="http://www.macosxhints.com/article.php?story=20090225065338303">easily bring them back</a>.</p>
</div>
<div class="section" id="silver-bindings">
<h2>Silver Bindings</h2>
<p>The one cool thing that really put a smile on my face when trying out
Safari 4 was discovering the new tab-switching keyboard shortcuts. It seems
like every app in the world has <a class="reference external" href="http://homepage.mac.com/bradster/iarchitect/tabs.htm">tabs these days</a>, and moving around between
them is the most common (yet also most application-specific) task you will
perform. Since the dawn of tab, developers haven&#8217;t been able to agree on a
global shortcut to switch tabs and my mouse has suffered great wear as the
battle rages on. I would guess this problem is a <a class="reference external" href="http://en.wikipedia.org/wiki/Not_Invented_Here">NIH</a> related artifact from
a time when tabs were the killer new feature to have, and no application had
yet proven to be the ubiquitous tab-interaction authority. I&#8217;ve always found
Safari 3&#8217;s built-in tab navigation key combo about as awkward as this
sentence. Firefox certainly paved the way with some very intuitive shortcuts,
but I only use Firefox for UI testing with Firebug, so rarely do I find myself
treading water in a sea of tabs. Also, Safari 4&#8217;s new developer tools have
pretty much guaranteed a serious decline in my Firebug time anyway.</p>
<p>With Safari 4, a great tab usage barrier has been shattered as the Firefox
<tt class="docutils literal"><span class="pre">control-tab</span></tt> shortcut replaces Safari&#8217;s original loathsome key combo.
I was so inspired by this move towards consistency (or additional Apple
rip-off attempt as one could claim) that I decided to add it to another
tab-defying application that I love so dearly: Coda.</p>
</div>
<div class="section" id="the-leopard-way">
<h2>The Leopard Way</h2>
<p>Mac OS X provides a System Preferences pane that allows you to add, edit and
remove global and application-specific keyboard shortcuts. It&#8217;s a handy
little tool found under the &quot;Keyboard &amp; Mouse&quot; preferences that somehow I&#8217;ve
only used once&#8230; to change tab behaviors. A while back, I actually had the
(impressively moronic) idea to change Coda&#8217;s tab shortcuts to <tt class="docutils literal"><span class="pre">command-tab</span></tt>
so switching between tabs would be &quot;as easy as switching applications.&quot; Now
<em>that&#8217;s</em> taking Coda&#8217;s &quot;one window development&quot; tagline to the eXtR3m#.</p>
<p>Luckily for me, Leopard doesn&#8217;t allow you to use the <tt class="docutils literal">tab</tt> key when
defining new shortcuts, so I settled for <tt class="docutils literal"><span class="pre">command-~</span></tt>, which is the standard
&quot;switch windows within application&quot; key command. &quot;Mostly one window
development&quot; turned out to be a real drag though, because I frequently work
on two or three Coda Sites at once, and found myself with no way to switch between
Sites. Bummer.</p>
<p>It was looking like Apple was going to deny me my tab nirvana.</p>
</div>
<div class="section" id="the-working-way">
<h2>The Working Way</h2>
<p>After poking around on Google, I discovered System Preferences stores
application shortcuts in your preferences <tt class="docutils literal">plist</tt>. It uses a dictionary
value named <tt class="docutils literal">NSUserKeyEquivalents</tt> to map the commands to the shortcuts
and can be changed easily with <tt class="docutils literal">defaults write</tt>. I also found that you
can use the <tt class="docutils literal">^</tt> character to represent the <tt class="docutils literal">control</tt> key when defining
your shortcuts, but what about <tt class="docutils literal">tab</tt>? Brute force experimentation landed me
in tab heaven on my first try. Here is how to make <tt class="docutils literal"><span class="pre">control-tab</span></tt> and
<tt class="docutils literal"><span class="pre">control-shift-tab</span></tt> map to &quot;Select Next Tab&quot; and &quot;Select Previous Tab&quot;
respectively in Coda:</p>
<div class="highlight"><pre><span class="gp">stewart:~ xdissent$</span> defaults write com.panic.Coda NSUserKeyEquivalents -dict-add <span class="s2">&quot;Select Next Tab&quot;</span> <span class="s1">&#39;^\t&#39;</span>
<span class="gp">stewart:~ xdissent$</span> defaults write com.panic.Coda NSUserKeyEquivalents -dict-add <span class="s2">&quot;Select Previous Tab&quot;</span> <span class="s1">&#39;^$\t&#39;</span>
</pre></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2009/02/28/safari-4-beta-and-coda-tabs-joy/feed/rss2/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fixing Paver</title>
		<link>http://xdissent.com/2009/02/24/fixing-paver/</link>
		<comments>http://xdissent.com/2009/02/24/fixing-paver/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 17:23:04 +0000</pubDate>
		<dc:creator>Greg Thornton</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Paver]]></category>

		<guid isPermaLink="false">http://xdissent.com/?p=1</guid>
		<description><![CDATA[


I&#8217;ve been a fan of Paver since the first time I read about it. It gives
me all of the control I want with just enough of an implied structure to keep
things sane and easy. The problem was, I couldn&#8217;t get the latest version,
which had many shiny new features. You know how I feel about shiny, [...]]]></description>
			<content:encoded><![CDATA[


<p>I&#8217;ve been a fan of <a class="reference external" href="http://www.blueskyonmars.com/projects/paver/">Paver</a> since the first time I read about it. It gives
me all of the control I want with just enough of an implied structure to keep
things sane and easy. The problem was, I couldn&#8217;t get the latest version,
which had many shiny new features. You know how I feel about <em>shiny</em>, so
I obviously needed to find a way to run Paver&#8217;s trunk, lest I invalidate
my work by targeting the almost-irrelevant current version.</p>
<span id="more-1"></span>
<p>Paver is such a flexible tool, it can present a chicken-and-egg packaging
dilemma by relying heavily on <em>itself</em> to build&#8230; <strong>itself</strong>. The packaged
1.0a1 was having trouble installing via <tt class="docutils literal">easy_install</tt> and <tt class="docutils literal">pip</tt> so I
had to figure out a way to build my own package. Unfortunately Paver&#8217;s
trunk has neither <tt class="docutils literal"><span class="pre">paver-minilib.zip</span></tt> nor <tt class="docutils literal">setup.py</tt> which means to
get things going, you have to use the current version of Paver. Of course,
the new alpha is so different, that the current release can&#8217;t handle it
and the build fails. I finally figured out a way to get a clean trunk
checkout installed and set out to squash the bug that got <a class="reference external" href="http://www.blueskyonmars.com/2009/01/29/paver-10a1-recalled/">1.0a1 recalled</a>
in the first place.</p>
<p>After poking around for a while, I believe paver&#8217;s option parsing methods
are confusing <tt class="docutils literal">distutils</tt> commands. It has to do with the way that options
are translated from the command line to Paver&#8217;s <tt class="docutils literal">options</tt>. I updated
<a class="reference external" href="http://code.google.com/p/paver/issues/detail?id=14">a relevant issue</a> on <a class="reference external" href="http://code.google.com/p/paver/">Paver&#8217;s project page</a> and attached a patch that fixes the
problem and allows Paver to build itself cleanly.</p>
<div class="section" id="the-fix">
<h2>The Fix</h2>
<p>Using <a class="reference external" href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>, <a class="reference external" href="http://pypi.python.org/pypi/virtualenvwrapper">virtualenvwrapper</a>, and Paver SVN <a class="reference external" href="http://code.google.com/p/paver/source/detail?r=37">r37</a>, I set up a clean
build environment for paver like so:</p>
<div class="highlight"><pre><span class="gp">stewart:~ xdissent$</span> <span class="nb">cd</span> ~/Code
<span class="gp">stewart:Code xdissent$</span> svn co http://paver.googlecode.com/svn/trunk/ paver-trunk
<span class="go">A    paver-trunk/.bzrignore</span>
<span class="go">A    paver-trunk/LICENSE.txt</span>
<span class="go">[...]</span>
<span class="go">A    paver-trunk/paver/doctools.py</span>
<span class="go">A    paver-trunk/paver/virtual.py</span>
<span class="go">U   paver-trunk</span>
<span class="go">Checked out revision 37.</span>
<span class="gp">stewart:Code xdissent$</span> <span class="nb">cd </span>paver-trunk
<span class="gp">stewart:paver-trunk xdissent$</span> mkvirtualenv paver-tmp
<span class="go">New python executable in paver-tmp/bin/python</span>
<span class="go">Installing setuptools............done.</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> add2virtualenv <span class="sb">`</span><span class="nb">pwd</span><span class="sb">`</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> python distutils_scripts/paver minilib generate_setup
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; paver.misctasks.minilib</span>
<span class="go">Generate paver-minilib.zip</span>
<span class="go">---&gt; paver.misctasks.generate_setup</span>
<span class="go">Write setup.py</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> mkvirtualenv paver-trunk
<span class="go">New python executable in paver-trunk/bin/python</span>
<span class="go">Installing setuptools............done.</span>
<span class="gp">(paver-trunk)stewart:paver-trunk xdissent$</span> rmvirtualenv paver-tmp
<span class="gp">(paver-trunk)stewart:paver-trunk xdissent$</span> python setup.py develop
<span class="go">python setup.py develop</span>
<span class="go">Paver 1.0a1</span>
<span class="go">warning: no files found matching &#39;*&#39; under directory &#39;paver/docs&#39;</span>
</pre></div>
<p>At this point I have Paver 1.0a1 installed in <em>development</em> mode, so the
new <tt class="docutils literal">paver</tt> binary is on my path <em>AND</em> changes I make to <tt class="docutils literal"><span class="pre">~/Code/paver-trunk</span></tt>
are effective immediately.</p>
<p>To demonstrate the problem, I created <tt class="docutils literal">options_test.py</tt>. Here&#8217;s a simple
task with some options:</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">paver.easy</span> <span class="kn">import</span> <span class="o">*</span>

<span class="n">options</span><span class="p">(</span>
   <span class="n">show_opts</span><span class="o">=</span><span class="n">Bunch</span><span class="p">(</span>
       <span class="n">foo_bar</span><span class="o">=</span><span class="s">&#39;default foobar&#39;</span><span class="p">,</span>
       <span class="n">no_foo</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
   <span class="p">),</span>
<span class="p">)</span>

<span class="nd">@task</span>
<span class="nd">@cmdopts</span><span class="p">([(</span><span class="s">&quot;foo-bar=&quot;</span><span class="p">,</span> <span class="s">&quot;f&quot;</span><span class="p">,</span> <span class="s">&quot;Foo bar value&quot;</span><span class="p">),</span>
         <span class="p">(</span><span class="s">&quot;no-foo&quot;</span><span class="p">,</span> <span class="s">&quot;n&quot;</span><span class="p">,</span> <span class="s">&quot;Foo negation&quot;</span><span class="p">)])</span>
<span class="k">def</span> <span class="nf">show_opts</span><span class="p">(</span><span class="n">options</span><span class="p">):</span>
   <span class="k">print</span> <span class="n">options</span><span class="o">.</span><span class="n">show_opts</span>
</pre></div>
<p>Since we have Paver 1.0a1, we can run the task with the <tt class="docutils literal"><span class="pre">-f</span></tt> option.
(Somebody said <em>somethin</em> about shiny new features.)</p>
<div class="highlight"><pre><span class="gp">(paver-trunk)stewart:tmp xdissent$</span> paver -f options_test.py show_opts
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo_bar=&#39;default foobar&#39;, no_foo=False)</span>
<span class="gp">(paver-trunk)stewart:tmp xdissent$</span> paver -f options_test.py show_opts --foo-bar<span class="o">=</span><span class="s1">&#39;new foobar&#39;</span> --no-foo
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo-bar=&#39;new foobar&#39;, foo_bar=&#39;default foobar&#39;, no-foo=True, no_foo=False)</span>
</pre></div>
<p>It becomes clear that <tt class="docutils literal">cmdopts</tt> definitions will never override default
options for this task. We can&#8217;t use <tt class="docutils literal"><span class="pre">foo-bar</span></tt> as an option name in our
Bunch, nor could we access the runtime value using
<tt class="docutils literal"><span class="pre">options.show_opts.foo-bar</span></tt>. It turns out distutils and setuptools
already noticed this problem and convert hyphens to underscores when
determining the storage variable&#8217;s name for an option. I&#8217;ve attached a
small patch for Paver SVN r37 that automatically makes this conversion.</p>
<div class="highlight"><pre><span class="gp">(paver-trunk)stewart:tmp xdissent$</span> patch -d ~/Code/paver-trunk -p0 -i options_fix.diff
<span class="go">patching file paver/setuputils.py</span>
<span class="go">patching file paver/tasks.py</span>
<span class="gp">(paver-trunk)stewart:tmp xdissent$</span> paver -f options_test.py show_opts
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo_bar=&#39;default foobar&#39;, no_foo=False)</span>
<span class="gp">(paver-trunk)stewart:tmp xdissent$</span> paver -f options_test.py show_opts --foo-bar<span class="o">=</span><span class="s1">&#39;new foobar&#39;</span> --no-foo
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo_bar=&#39;new foobar&#39;, no_foo=True)</span>
</pre></div>
<p>That&#8217;s more like it. I further tested the patch to confirm that distutil
commands receive their options correctly and that the easy_install problem
has been solved.</p>
<div class="highlight"><pre><span class="gp">(paver-trunk)stewart:paver-trunk xdissent$</span> paver minilib
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; paver.misctasks.minilib</span>
<span class="go">Generate paver-minilib.zip</span>
<span class="gp">(paver-trunk)stewart:paver-trunk xdissent$</span> mkvirtualenv paver-tmp
<span class="go">New python executable in paver-tmp/bin/python</span>
<span class="go">Installing setuptools............done.</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> python setup.py sdist
<span class="go">Paver 1.0a1</span>
<span class="go">warning: no files found matching &#39;*&#39; under directory &#39;paver/docs&#39;</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> easy_install dist/Paver-1.0a1.tar.gz
<span class="go">Processing Paver-1.0a1.tar.gz</span>
<span class="go">Running Paver-1.0a1/setup.py -q bdist_egg --dist-dir /var/folders/LU/LUPONriBGYepwd3i9FaBB++++TI/-Tmp-/easy_install-GnYR4C/Paver-1.0a1/egg-dist-tmp-iTfLMZ</span>
<span class="go">Paver 1.0a1</span>
<span class="go">running bdist_egg</span>
<span class="go">running egg_info</span>
<span class="go">[...]</span>
<span class="go">Adding Paver 1.0a1 to easy-install.pth file</span>
<span class="go">Installing paver script to /Users/xdissent/.virtualenvs/paver-tmp/bin</span>

<span class="go">Installed /Users/xdissent/.virtualenvs/paver-tmp/lib/python2.5/site-packages/Paver-1.0a1-py2.5.egg</span>
<span class="go">Processing dependencies for Paver==1.0a1</span>
<span class="go">Finished processing dependencies for Paver==1.0a1</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> which paver
<span class="go">/Users/xdissent/.virtualenvs/paver-tmp/bin/paver</span>
<span class="gp">(paver-tmp)stewart:paver-trunk xdissent$</span> <span class="nb">cd </span>tmp
<span class="gp">(paver-tmp)stewart:tmp xdissent$</span> paver -f options_test.py show_opts
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo_bar=&#39;default foobar&#39;, no_foo=False)</span>
<span class="gp">(paver-tmp)stewart:tmp xdissent$</span> paver -f options_test.py show_opts --foo-bar<span class="o">=</span><span class="s1">&#39;it works&#39;</span> --no-foo
<span class="go">Paver 1.0a1</span>
<span class="go">---&gt; pavement.show_opts</span>
<span class="go">Bunch(foo_bar=&#39;it works&#39;, no_foo=True)</span>
</pre></div>
<p>Hopefully 1.0 will come out soon, but until then you can <a class="reference external" href="http://paver.googlecode.com/issues/attachment?aid=-3172846000840253404&amp;name=options_fix.diff">download the patch</a>
and apply it from within <tt class="docutils literal">trunk</tt>:</p>
<div class="highlight"><pre><span class="gp">$</span> patch -p0 -i options_fix.diff
</pre></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://xdissent.com/2009/02/24/fixing-paver/feed/rss2/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
