<?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>Jeff Carouth&#039;s blog&#187; Input Validation</title>
	<atom:link href="http://carouth.com/tag/input-validation/feed/" rel="self" type="application/rss+xml" />
	<link>http://carouth.com</link>
	<description>Ramblings of a Web Application Developer</description>
	<lastBuildDate>Sat, 06 Feb 2010 21:36:18 +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>Excepting with the SPL</title>
		<link>http://carouth.com/2009/11/02/excepting-with-the-spl/</link>
		<comments>http://carouth.com/2009/11/02/excepting-with-the-spl/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 15:44:26 +0000</pubDate>
		<dc:creator>jcarouth</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Best Practice]]></category>
		<category><![CDATA[Input Validation]]></category>

		<guid isPermaLink="false">http://carouth.com/?p=117</guid>
		<description><![CDATA[In my opinion  proper use of error handling within an application is the mark of seasoned, professional developer. It is far too often that I see code that explodes on every error or, even worse, does not consider that errors will occur during runtime.
One area that I like to make use of exceptions is unexpected [...]]]></description>
			<content:encoded><![CDATA[<p>In my opinion  proper use of error handling within an application is the mark of seasoned, professional developer. It is far too often that I see code that explodes on every error or, even worse, does not consider that errors will occur during runtime.</p>
<p>One area that I like to make use of exceptions is unexpected input, especially in terms of function/method arguments. A lot of times the standard practice seems to be to return <em>FALSE</em> for invalid input, but the boolean value false should be reserved for boolean indication. Likewise, <em>NULL</em> should have a special connotation, semantically speaking.</p>
<p>In this first example, a repository (or mapper) is attempting to find a user with an id—let's assume it is a database id—that should be an integer. (<em>This code uses the Zend_Db_Table component to abstract queries, etc.</em>)</p>
<pre class="brush: php;">class UserRepository implements IRepository
{
 public function fetchById($id)
 {
     $data = $this-&gt;getDbTable()
                 -&gt;find($id)
                 -&gt;current();

     if (null === $data) {
         return null;
     }

     return new User($data-&gt;toArray());
 }
}</pre>
<p>Notice there is no validation performed on the <em>$id</em> parameter which is pushed directly into the database table query. Granted the <em>Zend_Db</em> component will handle this error with minimal pain, i.e., you should be fairly protected against a SQL injection attack, but you know that your database table uses an integer for the ID column thus your application should only respond positively to an  integer value for <em>$id</em>.</p>
<pre class="brush: php;">public function fetchById($id)
{
    if (!is_int($id)) {
        return false;
    }
    //…snip
}</pre>
<p>My first attempt (above) at validation uses the native <em>is_int()</em> validation function to check if the value supplied for <em>$id</em> is an integer. If it is not the function returns false. There is plenty of precedent behind using the value <em>FALSE</em> as the error state, but it is <strong>blatantly not semantic</strong>. <em>FALSE</em> is obviously not the user object I asked for, but it does not indicate what went wrong.</p>
<p>Finally, I decide to use the <em>Zend_Validate</em> component—for this trivial example it may be overkill, but it does the job nonetheless—to validate my input parameter for the user's ID property. Also notice that I am now throwing an exception object, specifically an <em>InvalidArgumentException</em>.</p>
<pre class="brush: php;">public function fetchById($id)
{
    $validator = new Zend_Validate_Int();
    if (!$validator-&gt;isValid($id)) {
        throw new InvalidArgumentException(
            'User ID must be an integer.
        );
    }
    //…snip
}</pre>
<p>The <em>InvalidArgumentException</em> exception is <a href="http://www.php.net/manual/en/spl.exceptions.php">one of many</a> defined in the <abbr title="Standard PHP Library">SPL</abbr> as an extension of a logic exception. The reason for using such an exception class would be to improve the readability and usefulness of client code. When I use the <em>UserRepository</em> object, my client code will look as follows. When an invalid argument, i.e., a non integer is given to the <em>fetchById()</em> method it is obvious which code path will execute.</p>
<pre class="brush: php;">try {
    $repository = new UserRepository();
    $user = $repository-&gt;fetchById(&quot;jcarouth&quot;);
} catch(InvalidArgumentException $e) {
    //we passed an invalid argument, i.e., a non-integer
} catch(Exception $e) {
    //some other
}</pre>
<div class="acc_license"><a href="http://creativecommons.org/licenses/by/3.0/"><img src="http://i.creativecommons.org/l/by/3.0/88x31.png" alt="by" /></a></div><!--<rdf:RDF xmlns="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><Work rdf:about=""><license rdf:resource="http://creativecommons.org/licenses/by/3.0/" /></Work><License rdf:about="http://creativecommons.org/licenses/by/3.0/"><requires rdf:resource="http://creativecommons.org/ns#Attribution" /><permits rdf:resource="http://creativecommons.org/ns#Reproduction" /><permits rdf:resource="http://creativecommons.org/ns#Distribution" /><permits rdf:resource="http://creativecommons.org/ns#DerivativeWorks" /><requires rdf:resource="http://creativecommons.org/ns#Notice" /></License></rdf:RDF>-->


Share:


	<a rel="nofollow"  target="_blank" href="http://www.printfriendly.com/print?url=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;partner=sociable" title="Print"><img src="http://carouth.com/wp-content/plugins/sociable/images/printfriendly.png" title="Print" alt="Print" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;title=Excepting%20with%20the%20SPL&amp;bodytext=In%20my%20opinion%C2%A0%20proper%20use%20of%20error%20handling%20within%20an%20application%20is%20the%20mark%20of%20seasoned%2C%20professional%20developer.%20It%20is%20far%20too%20often%20that%20I%20see%20code%20that%20explodes%20on%20every%20error%20or%2C%20even%20worse%2C%20does%20not%20consider%20that%20errors%20will%20occur%20during%20runti" title="Digg"><img src="http://carouth.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://delicious.com/post?url=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;title=Excepting%20with%20the%20SPL&amp;notes=In%20my%20opinion%C2%A0%20proper%20use%20of%20error%20handling%20within%20an%20application%20is%20the%20mark%20of%20seasoned%2C%20professional%20developer.%20It%20is%20far%20too%20often%20that%20I%20see%20code%20that%20explodes%20on%20every%20error%20or%2C%20even%20worse%2C%20does%20not%20consider%20that%20errors%20will%20occur%20during%20runti" title="del.icio.us"><img src="http://carouth.com/wp-content/plugins/sociable/images/delicious.png" title="del.icio.us" alt="del.icio.us" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;t=Excepting%20with%20the%20SPL" title="Facebook"><img src="http://carouth.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;title=Excepting%20with%20the%20SPL&amp;annotation=In%20my%20opinion%C2%A0%20proper%20use%20of%20error%20handling%20within%20an%20application%20is%20the%20mark%20of%20seasoned%2C%20professional%20developer.%20It%20is%20far%20too%20often%20that%20I%20see%20code%20that%20explodes%20on%20every%20error%20or%2C%20even%20worse%2C%20does%20not%20consider%20that%20errors%20will%20occur%20during%20runti" title="Google Bookmarks"><img src="http://carouth.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://reddit.com/submit?url=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;title=Excepting%20with%20the%20SPL" title="Reddit"><img src="http://carouth.com/wp-content/plugins/sociable/images/reddit.png" title="Reddit" alt="Reddit" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F&amp;title=Excepting%20with%20the%20SPL" title="StumbleUpon"><img src="http://carouth.com/wp-content/plugins/sociable/images/stumbleupon.png" title="StumbleUpon" alt="StumbleUpon" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://twitter.com/home?status=Excepting%20with%20the%20SPL%20-%20http%3A%2F%2Fcarouth.com%2F2009%2F11%2F02%2Fexcepting-with-the-spl%2F" title="Twitter"><img src="http://carouth.com/wp-content/plugins/sociable/images/twitter.png" title="Twitter" alt="Twitter" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://carouth.com/2009/11/02/excepting-with-the-spl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
