<?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>A.J. Brown&#039;s Blog</title> <atom:link href="http://ajbrown.org/blog/feed" rel="self" type="application/rss+xml" /><link>http://ajbrown.org/blog</link> <description>Coding adventures and technology musing for the masses</description> <lastBuildDate>Fri, 26 Mar 2010 17:57:50 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <item><title>Controlling Access with Zend Framework&#039;s Controller Plugins</title><link>http://ajbrown.org/blog/2010/03/20/controlling-access-with-zend-frameworks-controller-plugins.html</link> <comments>http://ajbrown.org/blog/2010/03/20/controlling-access-with-zend-frameworks-controller-plugins.html#comments</comments> <pubDate>Sat, 20 Mar 2010 18:56:53 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Zend Framework]]></category> <category><![CDATA[Zend_Auth_Identity]]></category> <category><![CDATA[Zend_Controller_Plugin]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=219</guid> <description><![CDATA[A common problem with developing web applications is controlling user access to certain sections or single pages. Zend Framework's Controller Plugin system provides a clean and efficient way to manage these checks, without muddling up your Controllers. Controller plug-ins are an extension of Zend_Controller_Plugin_Abstract. They allow you to modify the request (or perform any other [...]]]></description> <content:encoded><![CDATA[<p>A common problem with developing web applications is controlling user access to certain sections or single pages.  Zend Framework's Controller Plugin system provides a clean and efficient way to manage these checks, without muddling up your Controllers.</p><p>Controller plug-ins are an extension of <a href="http://framework.zend.com/apidoc/core/Zend_Controller/Plugins/Zend_Controller_Plugin_Abstract.html">Zend_Controller_Plugin_Abstract</a>.  They allow you to modify the request (or perform any other action) during any point in the <a href="http://bit.ly/9wzwei">Zend Framework request life-cycle</a>.  For more information about controller plug-ins themselves, visit the <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html">Zend Framework manual</a>.</p><p>Lets start out with the controller plugin itself.  The first thing we need to know is what point(s) of the request process lifecycle we should be operating on.  In our case, we need to know what controller and action the end user is requesting, so all routing must have occurred.  I chose to use preDispatch() because it ensures that an optimal amount of plugins have had their opportunity to make changes to the request, and gives us the highest chance of checking access to the final destination.  We can also catch any forwards from our action controller by performing the check here.</p><pre class="brush: php;">
&lt;?php
/**
 * A front controller plugin to check the current user against an access control list.
 *
 * @author A.J. Brown
 * @category Examples
 * @package Application_Controller
 * @subpackage Plugin
 * @version $Id$
 *
 */
class Application_Controller_Plugin_CheckHasAccess
    extends Zend_Controller_Plugin_Abstract
{

    public function preDispatch( Zend_Controller_Request_Abstract $request )
    {
        $isLoggedIn = Zend_Auth::getInstance()-&gt;hasIdentity();

        // Save some cycles if we're already logged in
        if( $isLoggedIn ) {
             return;
        }

 	$config     = $this-&gt;_getConfig();
        $action     = $request-&gt;getParam( 'action' );
        $controller = $request-&gt;getParam( 'controller' );

        // Make sure we don't end up in a loop
        if( $controller == $config-&gt;loginController
            &amp;&amp; $action == $config-&gt;loginAction )
        {
            return;
        }

        $secure = $this-&gt;_checkIsSecure(
			$request-&gt;getParam( 'action' )
			, $request-&gt;getParam( 'controller' )
		);

        if( $secure ) {
            $request-&gt;setParam( 'ref', $request-&gt;getPathInfo() );
            $request-&gt;setControllerName( $config-&gt;loginController );
            $request-&gt;setActionName( $config-&gt;loginController );
            $request-&gt;setDispatched( false );
        }
    }

    /**
     * Load the configuration.
     *
     * @return Zend_Config_Ini
     */
    protected function _getConfig()
    {
        static $config = null;
        if( null === $config ) {
            $config = new Zend_Config_Ini(
                APPLICATION_PATH . '/configs/access.ini' , 'global' );
        }
        return $config;
    }

    protected function _checkIsSecure( $action, $controller, $module = 'default' )
    {
        $config = $this-&gt;_getConfig();

        // If no match is found, what should be the default?
        $public = ( isset( $config-&gt;defaultAccess ) &amp;&amp; $config-&gt;defaultAccess == 'public' );

        // Check the action level, then controller
        if( isset( $config-&gt;controllers-&gt;$controller-&gt;actions-&gt;$action-&gt;access ) ) {
            $public = ( $config-&gt;controllers-&gt;$controller-&gt;actions-&gt;$action-&gt;access == 'public' );
        } elseif( isset( $config-&gt;controllers-&gt;$controller-&gt;access ) ) {
            $public = ( $config-&gt;controllers-&gt;$controller-&gt;access == 'public' );
        }

        return !$public;
    }
}
</pre><p>As you can see, the plug-in makes use of an ini configuration file to determine if a given controller and action is public or not.  If a setting for the action doesn't exist, we fall back to the controller's setting.  If the controller doesn't have a setting, we use whatever the default is.</p><p>Lets take a look at the configuration file.</p><pre class="brush: plain; wrap-lines: false;">
[global]

defaultAccess = &quot;private&quot;
loginController = &quot;index&quot;
loginAction = &quot;login&quot;

controllers.index.acccess = &quot;public&quot;
controllers.index.actions.profile.access = &quot;private&quot;

controllers.account.access = &quot;private&quot;
controllers.account.actions.confirm = &quot;public&quot;
</pre><p>In this configuration, all routes will be private unless they're specifically made private.  All of our actions within the "index" controller will be public, except for the "profile" action.  For the "account" controller, only the "confirm" action will be public.</p><p>The last step is making sure our plugin is registered with the front controller.  If we forget this part, our plug-in will never have a chance to intercept the request.  Registering can be done anywhere you want and at any point during the request process.  In fact, your plug-ins can even register other plug-ins.  The easiest and most common way is by adding an entry in our application.ini file for the FrontController resource.</p><pre class="brush: plain; highlight: [3]; wrap-lines: false;">
resources.frontController.controllerDirectory = APPLICATION_PATH &quot;/controllers&quot;
resources.frontController.params.displayExceptions = 0
resources.frontController.plugins.CheckHasAcess = &quot;Application_Controller_Plugin_CheckHasAccess&quot;
</pre><h2 id="toc-conclusion">Conclusion</h2><p>The nice part about designing an access control system using Zend Framework's controller plug-in system is that our code is separated from our controller code. Using this system, a developer doesn't necessarily have to concern himself with modifying the system.  Any new controllers that are added will automatically use the system without any additional code, and permissions can be changed quickly simply by modifying a configuration file.</p><p>Happy Coding!</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2010/03/20/controlling-access-with-zend-frameworks-controller-plugins.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>PHP 5.3 and Cake 1.2.0</title><link>http://ajbrown.org/blog/2009/12/22/php-5-3-and-cake-1-2-0.html</link> <comments>http://ajbrown.org/blog/2009/12/22/php-5-3-and-cake-1-2-0.html#comments</comments> <pubDate>Wed, 23 Dec 2009 03:33:30 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[CakePHP]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=212</guid> <description><![CDATA[I'm writing this quick note for anyone else that might come across this problem. I recently decided to upgrade one of my CentOS servers running a cleint's CakePHP application from a PHP 5.2.X version up to PHP 5.3.1. The package was from the remi repository, with no modifications. Suddenly, Cake stopped using my controllers' actions [...]]]></description> <content:encoded><![CDATA[<p>I'm writing this quick note for anyone else that might come across this problem.  I recently decided to upgrade one of my CentOS servers running a cleint's CakePHP application from a PHP 5.2.X version up to PHP 5.3.1.  The package was from the remi repository, with no modifications.  Suddenly, Cake stopped using my controllers' actions to generate output, and was displaying output from the default controller.</p><p>After pulling my head out, I found the issue in the dispatcher. Around line 359 or so (I hacked up my dispatcher with additional comments while debugging) in cake/Dispatcher.php, you will find the following:</p><p><code>$output = call_user_func_array(array(&#038;$controller, $params['action']), empty($params['pass'])? null: $params['pass']);</code></p><p>The problem is, call_user_func_array requires the 2nd parameter to be an array.  As you can see, cake is passing 'null' if we have no additional parameters to pass to the controller action.  To fix, just change 'null' to 'array()':</p><p><code>$output = call_user_func_array(array(&#038;$controller, $params['action']), empty($params['pass'])? array(): $params['pass']);</code></p><p>Now everything should be working again.</p><p>Note that this particular application is using a very early version of Cake 1.2.  This problem might be fixed in later versions.</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2009/12/22/php-5-3-and-cake-1-2-0.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>What does &quot;meeting the dealine&quot; mean to you?</title><link>http://ajbrown.org/blog/2009/05/02/what-does-meeting-the-dealine-mean-to-you.html</link> <comments>http://ajbrown.org/blog/2009/05/02/what-does-meeting-the-dealine-mean-to-you.html#comments</comments> <pubDate>Sat, 02 May 2009 20:18:12 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[Uncategorized]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=195</guid> <description><![CDATA[One of the most important aspects of maintaining good relationships is doing what you say you're going to do, when you say you're going to do it. As a software developer, your time to shine in this context is delivering the goods before your customer has to wonder where they are. It's equally important to [...]]]></description> <content:encoded><![CDATA[<p>One of the most important aspects of maintaining good relationships is doing what you say you're going to do, when you say you're going to do it.  As a software developer, your time to shine in this context is delivering the goods before your customer has to wonder where they are.</p><p>It's equally important to know what done means to the customer, and how it may conflict with your definition of done.  If I'm hiring you to line a parking lot for my store, and the deadline is the day of the grand opening, done is when the paint is dry, not when the last stroke is sprayed (and still wet!).  Since I don't paint asphalt for a living, you surely can't expect me to know how long it takes the paint to dry.</p><h3 id="toc-a-real-world-example">A Real World Example</h3><p>I once worked for an international online retailer who's idea of "meeting a deadline" was a little different than mine.  We were scheduled to do a major release of the website consisting of a brand new design, and some additional features.  It had a large supporting marketing campaign advertising it as a new generation of the store with super-awesome-o features.  A hard launch date was set in the marketing material and community hype, so launching on that date was critical.  The developers (through no fault of their own) ended up needing to work 20+ hour shifts in the days approaching the launch in order to make sure all of the promised features made the cut.  After gallons of coffee and mountain dew, the launch was finally completed at 11:50pm local time on the day of the deadline.</p><p>In the coming days, the launch was touted as a total success, and the words "we met the deadline" were strewn about the meeting halls by the software development managers.  I felt that expressing my opinion about the so called meeting of the deadline would create a lot of flak and would be taken as a slam to my fellow developers, so I decided to keep it to myself.</p><p>Quite frankly, this was not a satisfactory meeting of the deadline in my opinion.  The expectation as a customer of the site was that they would log-on on the launch date and see a brand new website with pretty little features.  Instead, we kept them waiting and wondering.  Our blog site for the store was lit up with comments by loyal customers, wondering where the site is. Many had given up on it being launched that day, and only those 7 hours behind GMT (the time zone any international company should be paying attention to) or greater actually saw the website on the launch date.  Yet, we were proud of meeting this tough deadline because "hey, we technically finish it on the date we promised!".</p><p>The real issue in the online retailer case is the approach to the problem.  The delivery date and the marketing campaign date should not have been the same.  The deadline for software development should have been at least 1 day prior to the launch, giving the developers a deadline that could be approached in the manner it was, but still allowing the site to actually be launched and available to the customer when they expected it to be.  The developers could push their efforts right up to the wire (as we did) without any negative impact.</p><h3 id="toc-conclusion">Conclusion</h3><p>You've probably heard the saying "If you're 5 minutes early, you're on time.  If you're on time, you're late!" or some similar version of it.  This saying definitely holds a lot of merit when it comes to delivering your products.  Surprise your customers and clients by delivering "5 minutes early" instead of making them come looking.  Don't use the vagueness of your own deadline as an excuse to say you delivered on time.  Save that for the cable company, and their "sometime between 9am and 5pm" appointments.</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2009/05/02/what-does-meeting-the-dealine-mean-to-you.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Zend_Service_PayPal Proposal Back on Track</title><link>http://ajbrown.org/blog/2009/02/03/zend_service_paypal-proposal-back-on-track.html</link> <comments>http://ajbrown.org/blog/2009/02/03/zend_service_paypal-proposal-back-on-track.html#comments</comments> <pubDate>Tue, 03 Feb 2009 19:01:37 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Zend Framework]]></category> <category><![CDATA[Zend_Service_PayPal]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=192</guid> <description><![CDATA[I just wanted to drop a quick note letting everyone know that after nearly 2 years of dormancy, Zend_Service_PayPal is back in the works. Shahar Evron has been too busy with his work over at Zend Technologies to continue work on the proposal, so I've volunteered my time to get it back on track. If [...]]]></description> <content:encoded><![CDATA[<p>I just wanted to drop a quick note letting everyone know that after nearly 2 years of dormancy, Zend_Service_PayPal is back in the works. <a href="http://prematureoptimization.org/blog/">Shahar Evron</a> has been too busy with his work over at Zend Technologies to continue work on the proposal, so I've volunteered my time to get it back on track.</p><p>If you're interested in seeing this component in Zend Framework soon, please follow progress at the <a href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Service_PayPal+-+A.J.+Brown">Zend Framework Contributors Wiki</a>, This blog, and on the <a href="http://github.com/ajbrown/zend_service_paypal" alt="GitHub Zend_Service_Paypal">project page at GitHub</a>.  Any feedback, suggestions, and patches you can provide will be nothing but useful.  Send me an email, comment on the wiki, or This proposal is still in it's early stages, but I hope to be knocking out a lot of the work in the next couple of weeks.</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2009/02/03/zend_service_paypal-proposal-back-on-track.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Learning What You Don&#039;t Know, So That You Do</title><link>http://ajbrown.org/blog/2009/01/30/learning-what-you-dont-know-so-that-you-do.html</link> <comments>http://ajbrown.org/blog/2009/01/30/learning-what-you-dont-know-so-that-you-do.html#comments</comments> <pubDate>Fri, 30 Jan 2009 20:53:01 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[Opinion]]></category> <category><![CDATA[Software Engineering]]></category> <category><![CDATA[PHP]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=185</guid> <description><![CDATA[It's been a very busy couple of weeks for me, and I've fallen behind on some of the articles I've promised to write. I've begun drafting them again, but I wanted to take some time out to talk about something a little more philosophical than technical. For me, learning the areas that I've yet to [...]]]></description> <content:encoded><![CDATA[<p>It's been a very busy couple of weeks for me, and I've fallen behind on some of the articles I've promised to write.  I've begun drafting them again, but I wanted to take some time out to talk about something a little more philosophical than technical.</p><p>For me, learning the areas that I've yet to master has been a huge motivation to keep pushing the envelope of my own knowledge.  I consider myself a very capable developer, and I don't feel that my co-workers, clients, or associates would say otherwise. At the same time, I know I still have a lot to learn.  In fact, anyone that says they're a master of every craft of web and software development probably hasn't learned enough to know what there is to know.  This blog itself is a consequence of my desire to explore more technologies and techniques.</p><p>The best gift I've been given recently is a true evaluation of my level of mastery.  This particular evaluation came interview-style from a Zend developer and client support specialist (meaning their salary is paid by Zend Technologies).  Before I entered the conversation, I knew it would be highly technical.  After all, you're talking about <em>the</em> PHP company.   I've been writing code in PHP for 7 years, am Zend Certified, ranked #3 on oDesk for the Advanced PHP Expert Rating test, placed top 10% in many other assessment tests on other freelance sites, yadda yadda yadda.  While none of this equates to guru, it does equate to experience and track record with the language.  Thus, I expected to be stumped occasionally, but stride through most of it as usual.</p><p>As you can imagine, that wasn't the case.</p><p>Overall, I did OK with the evaluation.  The questions that I was truly stumped on were things that only the best of the best would know off-hand (and even my evaluator admitted to not knowing the answer until he started working at Zend).  Then, of course, there were the middle-ground questions that I knew most of the answer to, but there was a small edge-case that I didn't think of, or that took me a bit of thinking to come up with.  But what surprised me the most were the questions that I did know (or should have known) off hand because I encounter them every day, but have been numb to the rhyme-or-reason of them.  I won't even mention getting a question wrong that I obviously knew the answer to, but was to worried about it being a trick question to think it all the way through.</p><p>I won't get into specifics of the questions that were asked, as I don't want to provide a cheat sheet for the next person.  But, the point is this -- being able to academically and fluently explain something on the spot is the true test of how in-depth your knowledge is on a subject.  Don't settle for just being able to do it well, but understand why you're doing it, how you did it, and what's the best way to do it.  The Pragmatic Programmers would call this programming by confidence, not coincidence.</p><p>Thanks for making me study harder, Zend <img src='http://ajbrown.org/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2009/01/30/learning-what-you-dont-know-so-that-you-do.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Automated Testing Using Zend Framework, Part 1</title><link>http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html</link> <comments>http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#comments</comments> <pubDate>Sun, 04 Jan 2009 20:05:41 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[PHPUnit]]></category> <category><![CDATA[Testing]]></category> <category><![CDATA[Zend Framework]]></category> <category><![CDATA[Zend_Test]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=157</guid> <description><![CDATA[Automated testing for your web applications is an important step in having the confidence to make changes to your application, and still be confident you're delivering a quality, regression-free product.  With Zend Framework's testing framework, you can build a thorough suite of test cases for your web application with very little hassle.]]></description> <content:encoded><![CDATA[<div class="toc"><ol><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-preparing-your-application">Preparing Your Application</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-a-basic-example">A Basic Example</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-running-your-tests">Running Your Tests</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-extending-the-testing-functionality">Extending the Testing Functionality</a><ol><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-disposable-testing-models">Disposable Testing Models</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-authentication-support">Authentication Support</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-putting-it-all-together">Putting It All Together</a></li></ol></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-writing-our-controller-test">Writing Our Controller Test</a></li><li><a href="http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html#toc-conclusion">Conclusion</a></li></ol></div><p>Automated testing for your web applications is an important step in having the confidence to make changes to your application, and still be confident you're delivering a quality, regression-free product.  With Zend Framework's testing framework (built with <a href="http://phpunit.de">PHPUnit</a>), you can build a thorough suite of test cases for your web application with very little hassle.</p><p>Part 1 will give you all of the basic information you need to start writing automated tests for your Zend Framework applications.   In Part 2, I'll provide more real-world example covering some other ways to write tests.</p><p>Lets get right to it.</p><p>For the examples below, I will be using an actual controller from one of my projects.  This controller handles account activies, such as logins, logouts, registrations, and confirmations.  We'll be using a test database with a schema that clones our production database, and Doctrine to manage ORM (Sorry Zend_Db <img src='http://ajbrown.org/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> ).  I'll assume that you're using the prescribed Zend Framework (1.6+) project layout, and that you're somewhat familiar with <a href="http://framework.zend.com/manual/en/zend.config.html" rel="nofollow">Zend_Config</a> and using an <a href="http://devzone.zend.com/article/3372-Front-Controller-Plugins-in-Zend-Framework">Initializer controller plugin</a> (created by default if you're using Zend Studio for Eclipse 6.1).</p><h3 id="toc-preparing-your-application">Preparing Your Application</h3><p>The first step to setting up automated testing is to prepare your application's environment and settings appropriately.  Depending no your setup, this can involve setting global variables, changing database connections, or reconfiguring paths.  Fortunately for us, this capability is easy using Zend_Config and an Initializer controller plugin.</p><p>Zend_Config allows you to specify "sections", which can inherit from another section.  This allows you to modify configuration for different environments without duplicating settings across different files (and thereby helping us ensure we don't forget to set something!).  In our example project, we'll need only to modify our database connection string, so we're using the test database.</p><pre class="brush: xml;">
&lt; ?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;config&gt;

&lt;production&gt;
  &lt;db&gt;
	&lt;dsn&gt;mysql://dbowner:password@localhost/maindb&lt;/dsn&gt;
	&lt;attributes&gt;
		&lt;model_loading&gt;conservative&lt;/model_loading&gt;
	&lt;/attributes&gt;
  &lt;/db&gt;
&lt;/production&gt;
&lt;test extends=&quot;production&quot;&gt;
  &lt;db&gt;
	&lt;dsn&gt;mysql://dbowner:password@localhost/maindb_test&lt;/dsn&gt;
  &lt;/db&gt;
&lt;/test&gt;
&lt;/config&gt;
</pre><p><sup>Notice how we can even inherit child attributes:  Even though we specified a a <db> node, we didn't have to specify everything below the </db><db> node</db></sup></p><p>Now that we have our configurations in order, we need something to manage this configuration for us, and switch off based on the environment we're running in.  That's the role of our Initializer plugin, which accepts the environment to initialize as a constructor parameter.  Showing the source of an Initializer is outside the scope of this article, but <a href="http://pastie.org/352285" rel="nofollow">here's a pastie for the curious</a>.</p><h3 id="toc-a-basic-example">A Basic Example</h3><p>Lets start with the basic framework of a controller test.  If you're using Zend Studio for Eclipse, you can easily create this structure by right-clicking on your controller in PHP Explorer and selecting<cite>New > Zend Framework Item</cite>, and then selecting<cite>Zend Controller Test Case</cite>.  Then, simply make sure the controller you want to test is chosen, and click finish.</p><pre class="brush: php;">
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';
require_once 'application/Initializer.php';
require_once 'application/default/controllers/IndexController.php';

class AccountControllerTest extends Zend_Test_PHPUnit_ControllerTestCase {

	/**
	 * Prepares the environment before running a test.
	 */
	protected function setUp() {
		$this-&gt;bootstrap = array ($this, 'appBootstrap' );
		parent::setUp ();
		// TODO Auto-generated FooControllerTest::setUp()
	}

	/**
	 * Prepares the environment before running a test.
	 */
	public function appBootstrap() {
		$this-&gt;frontController-&gt;registerPlugin ( new Initializer( 'test' ) );
	}

	/**
	 * Cleans up the environment after running a test.
	 */
	protected function tearDown() {
		// TODO Auto-generated FooControllerTest::tearDown()
		parent::tearDown ();
	}

	/**
	 * Constructs the test case.
	 */
	public function __construct() {
		// TODO Auto-generated constructor
	}

	/**
	 * Tests FooController-&gt;barAction()
	 */
	public function testIndexAction() {
		// TODO Auto-generated FooControllerTest-&gt;testBarAction()
		$this-&gt;dispatch ( '/index/index' );
		$this-&gt;assertController ( 'index' );
		$this-&gt;assertAction ( 'index' );
	}
}
</pre><p>You'll see on <strong>line 20</strong> where we're using our initializer to setup the test environment before we run the tests. Before each test metod is run, PHPUnit will call our<cite>setup()</cite> method, which has been programmed to call our appBootstrap method.  This ensures us that we're using a clean configuration and environment before each test, as if each test was a separate process.  When each test case is done, the<cite>tearDown()</cite> method is called.<cite>tearDown()</cite> is the place to put any code for removing resources or resetting any persistable changes that tests might make.  We'll make use of this in our advanced examples later.</p><p><strong>Line 41</strong> contains a bare-bones test case, which will ensure that dispatching to '/index/index' results in the controller named 'index' and an action called 'index' are the last to be executed.  This might seem trivial, but it helps detect errors with your controllers.  If an uncaught exception is thrown, the controller assertion will fail, since your controller will be the last executed.</p><h3 id="toc-running-your-tests">Running Your Tests</h3><p>To keep this article focused, I've decided to remove this section and cover only writing the tests.  If you need help creating Test Suites and running tests from the command line, check out <a rel="nofollow" href="http://www.phpunit.de/manual/3.3/en/">PHPUnit Documentation</a>, specifically the sections on <a rel="nofollow" href="http://www.phpunit.de/manual/3.3/en/textui.html">the Command Line Test Runner</a> and <a rel="nofollow" href="http://www.phpunit.de/manual/3.3/en/organizing-test-suites.html">Organizing Test Suites</a>.  If you have any specific questions, feel free to shoot me an email.</p><h3 id="toc-extending-the-testing-functionality">Extending the Testing Functionality</h3><p>Now that we covered the basics, lets get to fully testing our Accounts controllers.  There are a couple of "outside the box" requirements we have for testing our accounts controller.  First off, we need a way to test the full account creation process, as if a user was actually registering.  When we're done with a test, we want to get rid of that data whenever possible, so we can run tests as many times as we want and not worry about growing our test database.  Secondly, We need a way to simulate an authenticated user, as well as checking for whether a user has been authenticated or not.</p><p>Because these operations are pretty general and an opportunity for reuse exists, Lets put our supporting logic in a parent class and let our test cases inherit them.</p><h4 id="toc-disposable-testing-models">Disposable Testing Models</h4><p>There are two ways to ensure the data you're creating during a test is deleted once a test is complete.  Some choose to create the database on the fly using seed data.  Since I'm using Doctrine for my projects and working directly with models (no raw queries) in the tests, I decided that just deleting the data was the best approach.  To do this, all we need to do is "schedule" our model for deletion after it has been created (or loaded).</p><pre class="brush: php;">
protected function _setDisposable( Doctrine_Record $model )
{
    $this-&gt;_disposables[] = $model;
}
</pre><p>This function simply takes a reference to a model, and stores it in array, which will be handled by our tearDown() function later:</p><pre class="brush: php;">
	protected function tearDown()

	{
	    parent::tearDown();

	    foreach ( $this-&gt;_disposables as $model ) {
	        if ( $model instanceof Doctrine_Record ) {
	            $model-&gt;delete();
	        }
	        unset( $model );
	    }
	}
</pre><p>We simply loop through all of our "scheduled" models and delete them.  This must be done in tearDown() and not inside of any test method because it's the only way to ensure it happens.  Once an assertion fails or an unexpected exception occurs in a test, that method stops executing.  IF we were to try to dispose our models after an assertion, it may never happen<sup class='footnote'><a href='#fn-157-1' id='fnref-157-1'>1</a></sup>.   Similarly, we obviously can't dispose of a model <em>before</em> an assertion if that model is needed for the assertion (and why would it exist if you didn't need it?).</p><h4 id="toc-authentication-support">Authentication Support</h4><p>There are 3 things we must be able to do in order to fully test authentication.</p><ul><li>Create a fake identity</li><li>Set our environment to a state equivalent to a user being logged in.</li><li>Assert whether the environment has been changed to a logged in state.</li></ul><p>Our example controller uses a database adapter for authentication and identity retrieval<sup class='footnote'><a href='#fn-157-2' id='fnref-157-2'>2</a></sup>, so generating a fake identity for us means creating (or loading) a record in our accounts table, and returning the identity data we would normally get.</p><pre class="brush: php;">
/**
 * Generates a fake identity, usefull for simulating a logged in user
 *
 * @return StdClass an identity
 */
protected function _generateFakeIdentity()
{
	$identity = new stdClass();

        $account = new Account();
        $account-&gt;username     = 'AutoTest' . time();
        $account-&gt;emailAddress = 'autotest@example.org';
        $account-&gt;password     = md5( 'password' );
        $account-&gt;confirmed    = true;
        $account-&gt;enabled      = true;
        $account-&gt;save();
        $this-&gt;_setDisposable( $account );

	foreach( $account-&gt;toArray() as $key =&gt; $val ) {
	        $identity-&gt;$key = $val;
	}
	unset( $identity-&gt;password );

	return $identity;
}
</pre><p><cite>Account</cite> is our model, a<cite>Doctrine_Record</cite> type.  We're just simply creating a random account, and returning it's data as our idenity.  Notice that we're also scheduling this model for disposal (as we covered above.) Now, we just need a way to set our environment to the "logged in state" as this fake user.</p><pre class="brush: php;">
/**
 * Sets the current state as if there is a logged in user
 *
 * @param object $identity the idenity to use, otherwise one is generated
 * @return void
 */
protected  function _doLogin( $identity = null )
{
    if ( $identity === null ) {
        $identity = $this-&gt;_generateFakeIdentity();
    }
    Zend_Auth::getInstance()-&gt;getStorage()-&gt;write( $identity );
}
</pre><p>In our example application, if <a rel="nofollow" href="http://framework.zend.com/manual/en/zend.auth.html">Zend_Auth</a> has an identity, a user must be logged in.  Therefore, all we have to do is store an identity in Zend_Auth's storage adapter, and call ourselves logged in.  That makes asserting login as simple as checking for an identity.</p><pre class="brush: php;">
public function assertNotLoggedIn()
{
    $this-&gt;assertFalse( Zend_Auth::getInstance()-&gt;hasIdentity(), 'Login assertion failed' );
}

public function assertLoggedIn()
{
    $this-&gt;assertTrue( Zend_Auth::getInstance()-&gt;hasIdentity(), 'Login assertion failed' );
}
</pre><p>These simple assertions <sup class='footnote'><a href='#fn-157-3' id='fnref-157-3'>3</a></sup> ensure that we're logged in (or not logged in)</p><h4 id="toc-putting-it-all-together">Putting It All Together</h4><p>Putting it all together, we now have a base class which provides all of our test cases with the functionality we need.</p><pre class="brush: php;">
&lt; ?php

require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

class BaseControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{

    /**
     * Contains models which should be destroyed on tear down
     *
     * @var array
     */
    protected $_disposables = array();

	protected function tearDown()
	{
	    parent::tearDown();

	    foreach ( $this-&gt;_disposables as $model ) {
	        if ( $model instanceof Doctrine_Record ) {
	            $model-&gt;delete();
	        }
	        unset( $model );
	    }
	}

	/**
	 * Sets a model as disposable, so teardown automatically deletes it
	 *
	 * @param Doctrine_record $model
	 */
	protected function _setDisposable( Doctrine_record $model )
	{
	    $this-&gt;_disposables[] = $model;
	}

	/**
	 * Sets the current state as if there is a logged in user
	 *
	 * @param object $identity the idenity to use, otherwise one is generated
	 * @return void
	 */
	protected function _doLogin( $identity = null )
	{
	    if ( $identity === null ) {
	        $identity = $this-&gt;_generateFakeIdentity();
	    }

	    Zend_Auth::getInstance()-&gt;getStorage()-&gt;write( $identity );
	}

	/**
	 * Generates a fake identity, usefull for simulating a logged in user
	 *
	 * @param boolean $unique
	 * @return StdClass an identity
	 */
	protected function _generateFakeIdentity( $unique = false )
	{
		$identity = new stdClass();

		$account = new Account();
	        $account-&gt;username     = 'AutoTest' . time();
	        $account-&gt;emailAddress = 'autotest' . time() . '@example.org';
	        $account-&gt;password     = md5( 'password' );
	        $account-&gt;confirmed    = true;
	        $account-&gt;enabled      = true;
	        $account-&gt;save();
	        $this-&gt;_setDisposable( $account );

	    	foreach( $account-&gt;toArray() as $key =&gt; $val ) {
	        	$identity-&gt;$key = $val;
	    	}
	    	unset( $identity-&gt;password );

	    	return $identity;
	}

	public function assertNotLoggedIn()
	{
	    $this-&gt;assertFalse( Zend_Auth::getInstance()-&gt;hasIdentity(), 'Login assertion failed' );
	}

	public function assertLoggedIn()
	{
	    $this-&gt;assertTrue( Zend_Auth::getInstance()-&gt;hasIdentity(), 'Login assertion failed' );
	}

}
</pre><h3 id="toc-writing-our-controller-test">Writing Our Controller Test</h3><p>Now that our groundwork has been laid, we can finally start writing our controller test.</p><p>Our first set of test cases cover the requirement<cite>"when a user registers, they must confirm their email address before they can access their account"</cite>.  To do this, we need to simulate a user posting their valid registration details to our controller, and verify that the account created is not set as confirmed.  We then need to test that submitting login information for a non-confirmed account to our login action does not result in an authenticated user.</p><pre class="brush: php;">
public function testRegisterCreatesNewUnconfirmedAccount()
{
    $email = 'autotest' . time() . '@example.org';
    $data = array(
        'emailAddress'    =&gt; $email,
        'password'		  =&gt; 'testpassw0rd',
        'passwordconfirm' =&gt; 'testpassw0rd'
    );

    $_POST = $data;

    $this-&gt;dispatch( '/account/register' );
    //try to find the account record
    $table = Doctrine_Table::create( 'Account' ) ;
    $account = $table-&gt;findOneByEmailAddress( $email );
    $this-&gt;_setDisposable( $account );
    $this-&gt;assertNotNull( $account );
    $this-&gt;assertFalse( $account-&gt;confirmed, 'Account was not marked as unconfirmed' );
}

/**
 * Asserts that a user that hasn't been confirmed cannot login
 *
 */
public function testUnconfirmedUserCannotLogin()
{
    $email = 'autotest' . time() . '@example.org';

    $account = new Account();
    $account-&gt;username     = $email;
    $account-&gt;password     = md5( 'password' );
    $account-&gt;emailAddress = $email;
    $account-&gt;confirmed    = false;
    $account-&gt;enabled      = true;
    $account-&gt;save();

    $this-&gt;_setDisposable( $account );

    $_POST['username'] = $email;
    $_POST['password'] = 'password';

    $this-&gt;dispatch( '/account/login' );
    $this-&gt;assertFalse( Zend_Auth::getInstance()-&gt;hasIdentity() );
    $this-&gt;assertNotRedirect();
}
</pre><p>Our first test simply uses the $_POST global variable to simulate submitting our registration form with some test data.  After dispatch(), we use Doctrine_Table to find the model created by AccountController::registerAction(), then assert that the record was found and that it was not marked as confirmed.</p><p>The second test works by manually inserting a record that's not confirmed, and making sure no user is authorized when attempting to login with that user's account information.  As an added bonus, we also use<cite>assertNotRedirect()</cite> to make sure our controller didn't redirect.  Our controller should only redirect if login was successful, otherwise it would be confusing to a user.</p><h3 id="toc-conclusion">Conclusion</h3><p>Automated testing of your controllers is relatively simple using the combined power of PHPUnit and Zend Framework's Zend_Test component.  We can add additional functionality to allow our tests to simulate authentication, create fake identities, and even clean up our database after our tests have run.  I showed you how you can put this all together to test a registration and confirmation process in your controllers.</p><p>In part 2, I'll cover more areas of testing in our AccountsController, including testing our actions that require an authorized user in order to access them.</p><div class='footnotes'><div class='footnotedivider'></div><ol><li id='fn-157-1'>Of course, if tearDown() is never run for some reason the models won't be deleted either, but we have more control over this.  A third way that isn't discussed is creating an on_shutdown procedure, but that seems a little overkill <span class='footnotereverse'><a href='#fnref-157-1'>&#8617;</a></span></li><li id='fn-157-2'>I'm actually using ZendX_Doctrine_Auth_Adapter from the extras incubator <span class='footnotereverse'><a href='#fnref-157-2'>&#8617;</a></span></li><li id='fn-157-3'>Taknig this further, we should actually create new PHPUnit criteria instead of wrapping the assertTrue() criteria so that our failure message is different.  That's something for later, though <span class='footnotereverse'><a href='#fnref-157-3'>&#8617;</a></span></li></ol></div> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2009/01/04/automated-testing-using-zend-framework-part-1.html/feed</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Quick Doctrine ORM Tip: Hydration Using Doctrine_Table</title><link>http://ajbrown.org/blog/2008/12/31/hydration-using-doctrine-table.html</link> <comments>http://ajbrown.org/blog/2008/12/31/hydration-using-doctrine-table.html#comments</comments> <pubDate>Wed, 31 Dec 2008 12:00:53 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Doctrine ORM]]></category> <category><![CDATA[Doctrine_Record]]></category> <category><![CDATA[Doctrine_Table]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=120</guid> <description><![CDATA[Did you know you can have what Propel calls "Peers" in Doctrine PHP?  A peer is basically an object which is responsible for hydrating (populating) a model.  From the documentation, you might think this can only be done using DQL, but you can actually use Doctrine_Table to do the work for you.]]></description> <content:encoded><![CDATA[<p>Did you know you can have what Propel calls "Peers" in <a href="">Doctrine ORM</a>?  A peer is basically an object which is responsible for hydrating (populating) a model.  From the documentation, you might think this can only be done using DQL, but you can actually use Doctrine_Table to do the work for you.</p><p>The first thing you must do is define the model you want to be hydratable.  I'll use "Article" as my model.   This step is important because it gives Doctrine an object to hydrate when we perform operations against our Doctrine_Table object.  It also, of course, allows Doctrine to do alias translation and automatically detect relationships (I.E., so you don't have to manually perform joins.</p><pre lang="PHP" line="1">
class Article extends Doctrine_Record
{

	public function setTableDefinition()
	{

		$this->hasColumn( 'title', 'string', 255,
			array( 'notblank' => true )
		);

		$this->hasColumn( 'author', 'string', 255,
			array( 'notblank' => true )
		);

		$this->hasColumn( 'body', 'clob' );

		$this->hasColumn( 'published', 'boolean', null,
			array( 'default' => false )
		);
	}

	public function setUp()
	{
		$this->hasMany( 'Comment', array(
			'local' => 'id',
            		'foreign' => 'article_id',
		);
	}
}
</pre><p><sup>*It's good practice to make all of your models<cite>Timestampable</cite>, but I left that out of this example for simplicity</sup></p><p>Now that our models have been defined, lets move on to our Peer, the<cite>Doctrine_Table</cite>.  In it's simplest form, our Peer only needs to extend Doctrine_Table.  In order to harness the power of Doctrine out of the box, we need to <strong>make sure the 3rd parameter of the Doctrine_Table constructor is set to "<em>true</em>"</strong>.  This allows Doctrine to bind our model (defined above) to the Table that this Doctrine_Table instance is representing.   Without it, we would have to manually bind the model.</p><p><strong>TIP:</strong> Instead of doing this for every Peer, create a base class which does it for you.  I haven't run into a case yet where I didn't want to let Doctrine do it's work for me.  As long as the models exist, it should work fine.</p><pre lang="PHP" line="1">
class ArticlePeer extends Doctrine_Table
{

	public function __construct( Doctrine_Connection $oDbCon )
	{
		parent::__construct(  'Article', $oDbCon, true );
	}
}
</pre><p>Now that our peer is defined, we can save ourselves the trouble of writing any DQL.  Doctrine_Table makes available some magic functions, allowing you to do simple queries against any field defined in the model you're peering.  For example, we can easily retrieve a collection of Articles by "A.J. Brown":</p><pre lang="PHP" line="1">
$peer = new ArticlePeer( $connection );
$articles = $peer->findByAuthor( 'A.J. Brown' );
</pre><p>or all published articles:</p><pre lang="PHP" line="1">
$peer = new ArticlePeer( $connection );
$articles = $peer->findByPublished( true );
</pre><p>The advantage of this approach might not be obvious at first.  After all, you could just as easily instanciate a new Doctrine_Table, passing the correct parameters, right?</p><p>Most applications won't use the simple findBy<field> methods made availble through the Doctrine_Table API.   We'll typically need to do lookups that will require custom DQL to return the objects we need.  It's a good practice to make these queries reusable, and place them at a lower level in your code.  In fact, If you follow the "Fat Model, Skinny Controller" philosophy,  you would never be writing DQL at any level of your application outside of the model / data access layer. </field></p><p>With that said, any query that hydrates Article models (or agregate data of Article models, such as counts and averages) should be performed within a method of our ArticlePeer:</p><pre lang="PHP" line="1">
< ?php
class ArticlePeer extends Doctrine_Table
{

	public function __construct( Doctrine_Connection $oDbCon )
	{
		parent::__construct(  'Article', $oDbCon, true );
	}

	public function findArticlesForReview()
	{
		return $this->createQuery()
			->where( 'Article.pendingReview = true' )
			->addWhere( "Article.status != 'draft' ")
			->orderBy( "Article.title" )
			->execute()
			;
	}

}
</pre><p>Now our user code doesn't have to know the query needed for the data, it only needs to know what the method returns.  If your definition of an article pending review changes later, you won't need to grep through all of your code for the related queries.</p><p><strong>TIP:</strong> An added benefit of placing your DQL queries inside Doctrine_Table objects is caching.  The ArticlePeer above makes a great place to implement <a href="http://ajbrown.org/blog/tags/memcached">Memcached caching</a>, since it would be completely transparent to the user.</p><p>Happy Doctrine...ing?</p><p>For more basic information on using Doctrine, check the <a href="http://www.doctrine-project.org/documentation/manual/1_1/en/one-page#working-with-objects:fetching-data">Doctrine ORM Online Manual</a>.</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2008/12/31/hydration-using-doctrine-table.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>New Doctrine Patch: BETWEEN relation alias parsing</title><link>http://ajbrown.org/blog/2008/12/30/new-doctrine-patch-between-relation-alias-parsing.html</link> <comments>http://ajbrown.org/blog/2008/12/30/new-doctrine-patch-between-relation-alias-parsing.html#comments</comments> <pubDate>Tue, 30 Dec 2008 21:44:30 +0000</pubDate> <dc:creator>A.J. Brown</dc:creator> <category><![CDATA[PHP]]></category> <category><![CDATA[Doctrine ORM]]></category> <category><![CDATA[Doctrine_Query]]></category> <category><![CDATA[Doctrine_Query_Where]]></category><guid isPermaLink="false">http://ajbrown.org/blog/?p=151</guid> <description><![CDATA[Issue BETWEEN clauses with relational alias operands do not parse, resulting in an exception "could not find short alias". Example The following code will throw an exception. User hasOne Subscription. $q1 = Doctrine_Query::create() ->select('u.id') ->from('User u') ->where("CURRENT_DATE() BETWEEN u.Subscription.begin AND u.Subscription.end") ->addWhere( 'u.id != 5' ); Since the between operands are relational aliases, and not [...]]]></description> <content:encoded><![CDATA[<h4 id="toc-issue">Issue</h4><p>BETWEEN clauses with relational alias operands do not parse, resulting in an exception "could not find short alias".</p><h4 id="toc-example">Example</h4><p>The following code will throw an exception.  User hasOne Subscription.</p><pre lang="PHP" line="1">
$q1 = Doctrine_Query::create()
    ->select('u.id') ->from('User u') ->where("CURRENT_DATE() BETWEEN u.Subscription.begin AND u.Subscription.end")
    ->addWhere( 'u.id != 5' );
</pre><p>Since the between operands are relational aliases, and not literals or short aliases, Doctrine does not attempt to parse correctly.  I modified the behavior to do extra parsing on the expressions when BETWEEN is encountered as the operation.</p><h4 id="toc-the-goods">The Goods</h4><ul><li><a href="http://trac.doctrine-project.org/attachment/ticket/1792/fix-parse-between.diff">The Patch</a></li><li><a href="http://trac.doctrine-project.org/ticket/1792">The Ticket</a></li></ul><p>Guilherme from the team messaged me last night to let me know he's going to commit the patch.  I just checked and it's not there yet, so if you need this fix immediately, you can apply the patch above.</p> ]]></content:encoded> <wfw:commentRss>http://ajbrown.org/blog/2008/12/30/new-doctrine-patch-between-relation-alias-parsing.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> </channel> </rss>