<?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>john wyles dot com &#187; php</title>
	<atom:link href="http://johnwyles.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnwyles.com</link>
	<description>a man a plan a blog san francisco</description>
	<lastBuildDate>Tue, 08 Jun 2010 06:02:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP Magic Accessors Make Me Want to Punch Babies</title>
		<link>http://johnwyles.com/2010/02/10/php-magic-accessors-make-me-want-to-punch-babies/</link>
		<comments>http://johnwyles.com/2010/02/10/php-magic-accessors-make-me-want-to-punch-babies/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 06:30:18 +0000</pubDate>
		<dc:creator>John Wyles</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[accessors]]></category>
		<category><![CDATA[getter]]></category>
		<category><![CDATA[magic]]></category>
		<category><![CDATA[setter]]></category>
		<category><![CDATA[__get]]></category>
		<category><![CDATA[__set]]></category>

		<guid isPermaLink="false">http://johnwyles.com/?p=123</guid>
		<description><![CDATA[As many know PHP have dynamic methods (or magic methods) for producing an environment that, at run-time, is much different than one conceives at first blush.  It is largely the inclusion of these magic methods that brought PHP forward and lead to many elegant and inventive solutions.  These can be found in nearly [...]]]></description>
			<content:encoded><![CDATA[<p>As many know PHP have dynamic methods (or <a href="http://php.net/manual/en/language.oop5.magic.php">magic methods</a>) for producing an environment that, at run-time, is much different than one conceives at first blush.  It is largely the inclusion of these magic methods that brought PHP forward and lead to many elegant and inventive solutions.  These can be found in nearly every major framework and library that scatter the PHP landscape.  Indeed, they let you do very crafty things; take, for example, allowing for the custom <a href="http://framework.zend.com/code/browse/Zend_Framework/trunk/library/Zend/Controller/Action.php?r=8235#l463">dispatch of controller actions</a> in Zend Framework or how Doctrine uses them to <a href="http://trac.doctrine-project.org/browser/trunk/lib/Doctrine/ORM/Mapping/ClassMetadata.php?annotate=blame&#038;rev=7100#L311">perform serialized caching</a> for objects.  These examples really can really show off what PHP&#8217;s best intentions are.  However, like any tool, what it was intended for, and what others are using it for, in practice, can often be at odds.  My beef is with the magic accessors and the way I see them employed in many scenarios.</p>
<p>The use of the magic accessors (__get and __set) have allowed for the rapid growth and expansion of objects beyond anyones wildest dreams and now we are paying severely for the bloat and overhead.  On top of that, often coupled with this, is the lack of validation of values following overly optimistic assumptions about the values being set.  Let me show an example of such a class to make this more clear:</p>
<pre class="brush:php">
class User
{
    protected $_data=array();

    public function &#038;__get($key)
    {
        $value = null;
        if (isset($this->_data[$key])) {
            $value = $this->_data[$key];
        }

        return $value;
    }

    public function __set($key, $value)
    {
        $this->_data[$key] = $value;
    }

    public function __isset($key)
    {
        return isset($this->_data[$key]);
    }

    public function __unset($key)
    {
        unset($this->_data[$key]);
    }
}
</pre>
<p>What this now affords developers is the ability to, anywhere in code where they have a User object instance, create arbitrary invalidated values on the User object:</p>
<pre class="brush:php">
for($i=0; $i<1000000; $i++) {
    array_push($user->foo, new Foo($i));
}
$user->bar = 45.352135;
$user->baz = 'I CAN HAZ ANY VALUE I WANT! MUHAHAHA!';
$user->bat = memcache_get('some_invalid_value_from_mc');
// ...
var_dump(strlen(serialize($user))); // => 134523592
</pre>
<p>My argument centers around the misuse of these magic accessors, particularly in the case where you are persisting the object (as would most likely be the case for a User object). If you have a value you are putting into an object you should be able to, in a very straightforward manner, validate it (see my post <a href="/2010/01/21/a-tailored-approach-to-object-validation">A Tailored Approach to Object Validation</a>).  What better way than to explicitly specify an instance variable and a getter and setter method for it?  You can still use the magic accessors but perhaps as a catch all for values which seemed to appear out of thin air.  Take, for example, the way I think most setups should be done or modeled to closely resemble:</p>
<pre class="brush:php">
class User
{
    protected $_name;
    protected $_age;
    /* ... */

    public function getAge()
    {
        return $this->_age;
    }

    public function getName()
    {
        return $this->_name;
    }

    public function setAge($age)
    {
        $minimumAge = 0;
        $maximumAge = 130;
        $validator = new Validator_Integer_Between($minimumAge, $maximumAge);
        if (!$validator->valid($age)) {
            throw new ValidationException('The age attribute must be between the values [' . $minimumAge . '] and [' . $maximumAge . ']');
        }

        $this->_age = $age;
    }

    public function setName($name)
    {
        $regEx = "/^[A-Za-z]+$/";
        $validator = new Validator_String_Matches($regEx);
        if (!$validator->valid($name)) {
            throw new ValidationException('The name attribute must match the regular expression pattern [' . $regEx . ']');
        }

        $this->_name = $name;
    }

    public function __get($key)
    {
        throw new Exception('User::__get(' . $key . '): Attempt to get a non-existent attribute [' . $key . ']');
    }

    public function __set($key, $value)
    {
        throw new Exception('User::__set(' . $key . ', ' . $value . '): Attempt to set a non-existent attribute [' . $key . '] to value [' . $value . ']');
    }

    public function __isset($key)
    {
        throw new Exception('User::__isset(' . $key . '): Attempt to check for non-existent attribute [' . $key . ']');
    }

    public function __unset($key)
    {
        throw new Exception('User::__unset(' . $key . '): Attempt to unset a non-existent attribute [' . $key . ']');
    }
}
</pre>
<p>As you can see any value that &#8220;falls through the cracks&#8221; will be caught and dealt with.  In this way we are able to implement any craziness in the magic accessors, should we ever need do anything &#8220;magical&#8221;, and use concrete getters and setters so we are able to more readily (and cleanly) allow for the validation of every value set into our object, not to mention its also faster.  If you have a million values in your user object you should have at least two million accessor methods (1 million gets, and 1 million sets).  Adding a new attribute to the class, creating its getter method, and its setter method forces you to think about what you are doing and whether you need the value or not.</p>
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fjohnwyles.com%2F2010%2F02%2F10%2Fphp-magic-accessors-make-me-want-to-punch-babies%2F&amp;layout=button_count&amp;&amp;width=200&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:200px;height:40px;margin-top:5px;"></iframe>]]></content:encoded>
			<wfw:commentRss>http://johnwyles.com/2010/02/10/php-magic-accessors-make-me-want-to-punch-babies/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Simple Design for Organizing PHP Callbacks using Publish-Subscribe: Kestrel PubSub</title>
		<link>http://johnwyles.com/2010/02/03/a-simple-design-for-organizing-php-callbacks-using-publish-subscribe-kestrel-pubsub/</link>
		<comments>http://johnwyles.com/2010/02/03/a-simple-design-for-organizing-php-callbacks-using-publish-subscribe-kestrel-pubsub/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 05:31:42 +0000</pubDate>
		<dc:creator>John Wyles</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[kestrel]]></category>
		<category><![CDATA[kestrel_pubsub]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[publish-subscribe]]></category>
		<category><![CDATA[publisher]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[subscriber]]></category>

		<guid isPermaLink="false">http://johnwyles.com/?p=70</guid>
		<description><![CDATA[I&#8217;ve been rethinking an observer pattern I frequently employ and attempting to refactor the logic as a separate library.  It quickly occurred to me that the enterprise publish / subscribe (PubSub) pattern was essentially applicable to callback routines.  As a fun little experiment I decided to factor out each observable as a subscriber [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been rethinking an observer pattern I frequently employ and attempting to refactor the logic as a separate library.  It quickly occurred to me that the enterprise <a href="http://en.wikipedia.org/wiki/Publish/subscribe">publish / subscribe</a> (PubSub) pattern was essentially applicable to callback routines.  As a fun little experiment I decided to factor out each observable as a subscriber and to provide the publish and subscribe methods in a simple static class.  What resulted was <a href="http://github.com/johnwyles/Kestrel_PubSub">Kestrel PubSub</a>; a static singleton class that illustrates this simple, albeit powerful, pattern.</p>
<p>Suppose, for a minute, you have the method &#8220;postError&#8221; on the object &#8220;$client&#8221; which is of type &#8220;RESTClient&#8221; and the static method &#8220;log&#8221; on the class &#8220;Logger&#8221;.  To nicely wrap up both of these to receive a publish action denoted by the subject, say &#8220;invalid_password&#8221;, we would do the following:</p>
<pre class="brush:php">
// Setup the REST client
$client = new RESTClient('127.0.0.1', 80);

// Subscribe the REST client
Kestrel_PubSub::subscribe('invalid_password', $client, 'postError');

// Subscribe the Logger
Kestrel_PubSub::subscribe('invalid_password', 'Logger', 'log');
</pre>
<p>Later in the code where we want to publish to our subscribers, the string argument &#8216;Invalid password supplied&#8217;, we then simply do the following:</p>
<pre class="brush:php">
Kestrel_PubSub::publish('invalid_password', 'Invalid password supplied.');
</pre>
<p>That&#8217;s it!  There are a few other API methods for managing these subscriptions, but shown here is the simplest use case.  I should mention to those interested in this pattern that Matthew Weier O&#8217;Phinney&#8217;s <a href="http://weierophinney.net/matthew/archives/199-A-Simple-PHP-Publish-Subscribe-System.html">A Simple PHP Publish-Subscribe System</a> has a markedly similar implementation to this one and is worth researching depending on your needs.  The one I have shown here, <a href="http://github.com/johnwyles/Kestrel_PubSub">Kestrel PubSub</a>, is a bare-bones implementation with very little object overhead and kept intentionally simplistic.  The main difference of note between the two implementations, is that Matthew&#8217;s implementation returns a subscriber handle while mine does not.  This is a nice convenience if you expect to remove subscribers, but I have yet to come up with the use case practically.  Likewise discarding this convenience can greatly increase the simplicity and clarity.  I did decide, at the last minute, to include an unsubscribe but instead of using a handle to unsubscribe a subscriber the unscubscribe method takes the original context in which the subscriber was added to remove it from the subscribers.  I feel this is a very healthy compromise, but that could be subject to change as I continue to expand use of this pattern.</p>
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fjohnwyles.com%2F2010%2F02%2F03%2Fa-simple-design-for-organizing-php-callbacks-using-publish-subscribe-kestrel-pubsub%2F&amp;layout=button_count&amp;&amp;width=200&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:200px;height:40px;margin-top:5px;"></iframe>]]></content:encoded>
			<wfw:commentRss>http://johnwyles.com/2010/02/03/a-simple-design-for-organizing-php-callbacks-using-publish-subscribe-kestrel-pubsub/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Tailored Approach to Object Validation</title>
		<link>http://johnwyles.com/2010/01/21/a-tailored-approach-to-object-validation/</link>
		<comments>http://johnwyles.com/2010/01/21/a-tailored-approach-to-object-validation/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 21:50:29 +0000</pubDate>
		<dc:creator>John Wyles</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[bulk]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[symfony]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://johnwyles.com/?p=24</guid>
		<description><![CDATA[I was thinking some on object validation this afternoon and found out quickly that I wanted my cake and the ability to eat it to.  Namely that I wanted to be able to statically validate values for a given attribute and also contextually validate values in PHP&#8217;s magic setter.  Statically validating values for [...]]]></description>
			<content:encoded><![CDATA[<p>I was thinking some on object validation this afternoon and found out quickly that I wanted my cake and the ability to eat it to.  Namely that I wanted to be able to statically validate values for a given attribute and also contextually validate values in PHP&#8217;s magic setter.  Statically validating values for attributes was a requirement as often instantiation of the object came with significant overhead (e.g. fetching from Memcache, trip to the database, etc.) so accessing its validators statically could be used to validate the setup of the object prior to its creation.  Not to mention the bulk static validation operations could be run for a digest of object attributes, say, in a flat CSV file for instance.  Here are the set of class I came up with:</p>
<pre class="brush:php">
/**
 * Generic validation (e.g. code generated) would go here
 */
abstract class Foo_Abstract_Autogenerated
{
    public static function auto_validate_bar($bar)
    {
        $validator = new Validator_Integer_Between(1, 100);
        if ($validator->valid($bar)) {
            return true;
        }

        return false;
    }
}

/**
 * Custom validation (e.g. business logic / interdependencies ) would go here
 */
abstract class Foo_Abstract extends Foo_Abstract_Autogenerated
{
    public function validate_bar($bar)
    {
        if (in_array($bar, $this->_bannedBarValues)) {
            return false;
        }

        return true;
    }
}

class Foo extends Foo_Abstract
{
    protected $_bannedBarValues = array(1, 2, 3);

    public function valide($fieldName, $value)
    {
        if (method_exists($this, 'validate_' . $fieldName)) {
            $returnValue = call_user_func_array(array($this, 'auto_validate_' . $fieldName), $value);
            if ($returnValue) {
                $returnValue = call_user_func_array(array($this, 'validate_' . $fieldName), $value);
            }
        }

        return $returnValue;
    }
}
</pre>
<p>This now affords me the luxury of being able to do the following:</p>
<pre class="brush:php">
// Does a value validate in static context?
$bar = $_REQUEST['bar'];
$valid = Foo::auto_validate_bar($bar);

// Does a value validate against the business logic?
$bar = $_REQUEST['bar'];
$valid = $foo->validate_bar($bar);

// Does the current instance value validate against the business logic?
$valid = $foo->validate_bar($foo->bar);

// Does the current instance value validate against both generic and business logic?
$valid = $foo->validate('bar', $foo->bar);
</pre>
<p>Now I can afford myself the luxury of autogenerating a generic class, in similar fashion to <a href="http://www.symfony-project.org/book/1_2/10-Forms#chapter_10_sub_standard_symfony_validators">Symfony validators</a>, to accomplish the validation for the Foo object.</p>
<p>What do you folks think?</p>
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fjohnwyles.com%2F2010%2F01%2F21%2Fa-tailored-approach-to-object-validation%2F&amp;layout=button_count&amp;&amp;width=200&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:200px;height:40px;margin-top:5px;"></iframe>]]></content:encoded>
			<wfw:commentRss>http://johnwyles.com/2010/01/21/a-tailored-approach-to-object-validation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP_CodeCoverage</title>
		<link>http://johnwyles.com/2010/01/15/php_codecoverage/</link>
		<comments>http://johnwyles.com/2010/01/15/php_codecoverage/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 22:42:33 +0000</pubDate>
		<dc:creator>John Wyles</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[code sniffer]]></category>
		<category><![CDATA[coverage]]></category>
		<category><![CDATA[cruise control]]></category>
		<category><![CDATA[phpundercontrol]]></category>
		<category><![CDATA[phpunit]]></category>

		<guid isPermaLink="false">http://johnwyles.com/?p=8</guid>
		<description><![CDATA[Just finished reading Sebastian Bergmann&#8217;s post CRAP in PHPUnit and am excited to see code coverage broken out into a separate library: PHP_CodeCoverage.  Excited to get CruiseControl, phpUnderControl, PHP_CodeSniffer, PHPUnit, and now PHP_CodeCoverage all rolled in together to push quality to the extreme.
]]></description>
			<content:encoded><![CDATA[<p>Just finished reading Sebastian Bergmann&#8217;s post <a href="http://sebastian-bergmann.de/archives/877-CRAP-in-PHPUnit-3.5.html">CRAP in PHPUnit</a> and am excited to see code coverage broken out into a separate library: <a href="http://github.com/sebastianbergmann/php-code-coverage">PHP_CodeCoverage</a>.  Excited to get <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a>, <a href="http://phpundercontrol.org/">phpUnderControl</a>, <a href="http://pear.php.net/package/PHP_CodeSniffer">PHP_CodeSniffer</a>, <a href="http://www.phpunit.de/">PHPUnit</a>, and now <a href="http://github.com/sebastianbergmann/php-code-coverage">PHP_CodeCoverage</a> all rolled in together to push quality to the extreme.</p>
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fjohnwyles.com%2F2010%2F01%2F15%2Fphp_codecoverage%2F&amp;layout=button_count&amp;&amp;width=200&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:200px;height:40px;margin-top:5px;"></iframe>]]></content:encoded>
			<wfw:commentRss>http://johnwyles.com/2010/01/15/php_codecoverage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
