<?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>Rich Buggy &#187; zend framework</title>
	<atom:link href="http://buggy.id.au/tag/zend-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://buggy.id.au</link>
	<description>Developer, Manager, Entrepreneur</description>
	<lastBuildDate>Sat, 22 May 2010 12:09:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Migrating to the Zend Framework</title>
		<link>http://buggy.id.au/2009/07/15/migrating-to-the-zend-framework/</link>
		<comments>http://buggy.id.au/2009/07/15/migrating-to-the-zend-framework/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 01:57:02 +0000</pubDate>
		<dc:creator>Rich</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[sydphp]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://www.buggy.id.au/?p=247</guid>
		<description><![CDATA[I don&#8217;t usually blog about work but I think this may interest some people. Late last year we trialled the Zend Framework in a small application. A few months ago we begun the process of converting our main PHP application to it. The migration is still in the early stages so some of this may change [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t usually blog about work but I think this may interest some people. Late last year we trialled the Zend Framework in a small application. A few months ago we begun the process of converting our main PHP application to it. The migration is still in the early stages so some of this may change rapidly.</p>
<p>We decided on the Zend Framework because it was component based. This was important because we have an existing code base with a regular release schedule. Stopping development while we converted the application wasn&#8217;t an option so we needed something that could be integrated slowly.</p>
<p>So how are we doing this?</p>
<p>The first task was to replace the applications module structure with auto loading. While this reduced the number of files that needed to be included to process a request the biggest advantage was making the code more visible to the developers. Prior to this classes were hidden 2, 3 or 4 levels deep in modules. The immediate impact was finding a number of classes that were no longer required.</p>
<p>Next I was expecting to replace some of the more discrete components like logging but it didn&#8217;t turn out this way. Because of the applications development schedule work instead focused on migrating from our custom MVC to the Zend Framework MVC.</p>
<p>After writing a bootstrap file  we created controllers and actions. The release cycle wasn&#8217;t long enough to completely convert the old MVC so the new actions simply call the old code. This approach allowed us convert the front controller (without session management and authentication) in about a day and means that new code can be written using the Zend Framework instead of our old framework.  Custom routing was required to emulate some of the old URLs.</p>
<p>The session management and authentication took about to day to sort out on its own. All of the controllers share a common base class. It&#8217;s init() function provides some common functionality:</p>
<ol>
<li>Initialize the view</li>
<li>Initialize the session (except the API or AJAX controllers)</li>
<li>Set all actions as requiring authentication</li>
</ol>
<p>Starting sessions is done in the controllers init() function instead of the bootstrap file so we can prevent sessions from being started for API calls. This is important because we get a large number of API calls and none of them requires a session. The other important task for init() is to mark some actions as not requiring authentication.</p>
<p>Authentication itself takes place in the controllers preDispatch() function. This provided backwards compatibility with the way the application previously worked.</p>
<p>More recently we&#8217;ve begun removing static methods from business logic so that we can use dependency injection to make testing easier. I&#8217;ll post about this next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://buggy.id.au/2009/07/15/migrating-to-the-zend-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic forms using Zend_Form</title>
		<link>http://buggy.id.au/2009/06/21/dynamic-forms-using-zend-form/</link>
		<comments>http://buggy.id.au/2009/06/21/dynamic-forms-using-zend-form/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 02:31:12 +0000</pubDate>
		<dc:creator>Rich</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[sydphp]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://www.buggy.id.au/?p=260</guid>
		<description><![CDATA[While most forms contain fixed fields there are occasions when you need a form to be dynamic and adjust itself based on user input. The adjustment could be as simple as altering the options in a drop down list or as complex as adding/removing fields. In this post I&#8217;m going to cover how to create [...]]]></description>
			<content:encoded><![CDATA[<p>While most forms contain fixed fields there are occasions when you need a form to be dynamic and adjust itself based on user input. The adjustment could be as simple as altering the options in a drop down list or as complex as adding/removing fields. In this post I&#8217;m going to cover how to create a dynamic form using Zend_Form and jQuery. I&#8217;ll use the example of a registration form that prompts the user for their country and state. The requirements are pretty simple:</p>
<ol>
<li>It should only prompt for a state if the country has states.</li>
<li>The state list should only show states for the selected country.</li>
<li>The form should degrade gracefully so it works without Javascript</li>
</ol>
<p>To start I&#8217;m going to create a World class. This class has two functions. The first returns a list of countries. The second returns a list of states for a specified country or a list of all countries that have states plus the states in those countries. You might like to retrieve this information from a database but for simplicity I&#8217;ll hard code the information into the class.</p>
<pre>class World
{
    static private $_countries = array(
                       "AU" =&gt; "Australia",
                       "NZ" =&gt; "New Zealand");

    static private $_states = array(
		        "AU" =&gt; array(
		            "ACT" =&gt; "Australian Capital Territory",
		            "NSW" =&gt; "New South Wales",
		            "NT" =&gt; "Northern Territory",
		            "QLD" =&gt; "Queensland",
		            "SA" =&gt; "South Australia",
		            "TAS" =&gt; "Tasmania",
		            "VIC" =&gt; "Victoria"));

    public function getCountries()
    {
        return self::$_countries;
    }

    public function getStates($country = null)
    {
        if ($country === null) {
            return self::$_states;
        }
        if (array_key_exists($country, self::$_states)) {
            return self::$_states[$country];
        }
        return null;
    }
}</pre>
<p>Next I&#8217;ll create a class for the form (RegForm) by extending Zend_Form. This gives our registration form all of the advantages you get from Zend_Form including input filtering and validation. The form elements will be added in the constructor so that creating a new form is all you need to do to use it.</p>
<p>As our form needs to adapt based on user input the constructor needs to accept the user input as one of its parameters. This allows us to adjust the form elements based on the user input. All code using these parameters needs to be extremely careful as the user input has not been filtered or validated yet.</p>
<pre>class RegForm extends Zend_Form
{
    public function __construct($world, $params)
    {
        parent::__construct();

        $countries = $world-&gt;getCountries();
        $countryKeys = array_keys($countries);
        $thisCountry = isset($params['country']) ? $params['country'] : $countryKeys[0];
        $states = $world-&gt;getStates($thisCountry);

        $country = new Zend_Form_Element_Select('country');
        $country-&gt;setLabel('Country')
                -&gt;setMultiOptions($countries)
                -&gt;setValue($thisCountry)
                -&gt;setRequired(true);
        $this-&gt;addElement($country);

        $state = new Zend_Form_Element_Select('state');
        $state-&gt;setLabel('State');
        if ($states !== null) {
            $state-&gt;setMultiOptions($states)
                  -&gt;setRequired(true);
        } else {
            $state-&gt;setRegisterInArrayValidator(false);</pre>
<pre>        }
        $this-&gt;addElement($state);

        $submit = new Zend_Form_Element_Submit('submit');
        $submit-&gt;setValue('Add User')
               -&gt;setRequired(false);
        $this-&gt;addElement($submit);
    }
}</pre>
<p>There are two important things that RegForm does:</p>
<ol>
<li>The state options are adjusted to match the selected country.</li>
<li>The state is not validated if the country does not contain states.</li>
</ol>
<p>This means that our form will work exactly the way you expect Zend_Form to work. Without Javascript if you select a country and submit the form then the state list will adjust and display an error that the previously selected state was invalid. After you select a valid country and state the form will validate. If the selected country does not have states then the form with validate regardless of the selected state (providing there are no other errors).</p>
<p>I then need to create the controller.</p>
<pre>class AccountController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $params = $this-&gt;_getAllParams();
        $world = new World();
        $form = new RegForm($world, $params);</pre>
<pre>        if ($this-&gt;_request-&gt;isPost() &amp;&amp; $form-&gt;isValid($params)) {
            // The form was valid!!
        }
        $this-&gt;view = $form;
    }
}</pre>
<p>Finally we can add Javascript to alter the form in browser. If you&#8217;re using the forms render() function then the Javascript will look something like this.</p>
<pre>    var countries = &lt;?php echo json_encode($this-&gt;world-&gt;getCountries()); ?&gt;;

    var states = &lt;?php echo json_encode($this-&gt;world-&gt;getStates()); ?&gt;

    function updateStates() {
        var state = $("#state");
        var country = $("#country");
        var hasStates = false;
        jQuery.each(states, function (cc, slist) {
            if (cc == country.val()) {
                hasStates = true;
                state.html('');
                jQuery.each(slist, function (code, name) {
                    state.append('&lt;option value="' +  code + '"&gt;' + name + '&lt;/option&gt;');
                });
            }
        });
        if (hasStates) {
            $("#state-label").css("display", "block");
            $("#state-element").css("display", "block");
        } else {
            $("#state-label").css("display", "none");
            $("#state-element").css("display", "none");
        }
    }</pre>
<pre>    $().ready(function () {
        $("#country").change(function () {
            updateStates();
        });
        var state = $("#state");
        if (state.val() == null) {
            $("#state-label").css("display", "none");
            $("#state-element").css("display", "none");
        }
    });</pre>
<p>This code takes care of hiding the states if they are not required and adjusting the states based on the selected country without needing to submit the form. With minimal effort I&#8217;ve been able to create a dynamic form using Zend_Form to do most of the hard work. Users with Javascript enabled get an A grade experience while those without Javascript can still use the form.</p>
]]></content:encoded>
			<wfw:commentRss>http://buggy.id.au/2009/06/21/dynamic-forms-using-zend-form/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
