In Development (and life) we should learn to embrace failures…

i’m enjoying my time at ZendCon 2010. I spent all day Monday in Christian Wenz’s PHP Certification Bootcamp. This was an extensive overview on the kinds of questions that appear on the PHP 5.3 certification exam as well as some exam strategies and “gotchas” to look out for. My exam was was scheduled for Tuesday night, and as the Bootcamp wore on I became more aware of my knowledge limitations as a PHP developer.

So Tuesday evening came and I went to take the Exam. After the Bootcamp, which was 5.3 focused, I would have liked to switch my exam from PHP 5 to the 5.3 test, but the exam proctor informed me this was locked in from my prior-indicated preference.

To make a long story short, I FAILED. A bit insecure at first, I spent the night processing this now fact and woke up with a healthy perspective.

I remember a Nike ad from 1998 with Michael Jordan where he stated all the shots he’s missed in his career, including how many game winners he missed, and he simply said at the end “Failure is how I succeed.”

In development as well as life in general, it is important to understand our limitations, our weaknesses, and our opportunities for growth and improvement. If never tested, we can never grow. Fear of failure is simply a fear of growth and improvement.

Other thoughts on this is that being a PHP developer is not my life, its a part of my life. I’ve been doing this stuff for four years and I had a life before PHP and a life after. I still think the ZCE is important for the community as it lends legitimacy, and it is still a personal goal of mine, but it does help me to remember that faith and family are bigger pieces of my life in a absolute sense, and my professional life is really an expression of my larger self and not the other way around.

I now understand where my weaknesses in PHP are, and therefore where to focus going forward. What failure has provided in this case is information I can now act on.

Anyway, its not typical for me to dump my soul on this blog or anywhere on the interweb, but I figured I’m probably not the only one here at ZendCon that failed the test and therefore probably also not the only one processing the outcome.

Chris

Source and Powerpoint from AJAX Made Easy with jQuery

As promised, attached is the source code and presentation from my presentation/demo yesterday. You’ll need a PHP capable web server to run the cities.php file. However, by using a simple txt file with a static JSON string of cities, you could pass the entire city list to your javascript function and do the search filtering there instead of on the server side. Just a thought…

Presentation
Source Code

Sunsetting IE6 on your own

Anyone that does front end web development or web design hates Internet Explorer 6.  Why?  First released in 2001, IE6 is dog slow, very buggy, and essentially completely non-standards compliant.

These issues manifest themselves in two primary categories as best I can tell:  javaScript bugs/behaviors, and layout/CSS behaviors or missing features.

So, developers learn to code around these things.  In CSS this means a lot of hacks and html conditional statements to load custom css, js and htc files to fix many CSS-related deficiencies such as the lack of 24-channel PNG transparency.  As to JavaScript, I’ve found that jQuery cures the need for IE6-specific code, but we continue to see IE6-specific bugs/glitches that are difficult or impossible to isolate, duplicate, or fix.

Unfortunately for enterprise developers, our users seem to be behind the curve when compared to browser adoption. Much of our target audience is still on Windows XP, and depending on IT policies and budget constraints, abandonment of IE6 in the enterprise has lagged behind the consumer segment.

In the enterprise environment I work in, my primary application sees about 200 visits per day across the institution.  About a year ago I began a crusade (no, that is not too strong of a word when the context is IE6) to purge IE6 from the realm of users accessing my web apps.  I had three goals in mind: 1) Reduce userland bugs/glitches and errors caused by IE6, 2) Improve the overall user experience via a superior browser, and 3) Reduce the amount of time I have to spend working around IE6’s craptasticness.

I have to give this caveat before continuing further: As my institution has begun deploying Win7 machines, our IE6 usage has plummeted like a brick.  Admittedly this is the biggest single factor in the reduction of IE6 users against my web apps.  However, there is something to be said for encouraging your users to upgrade and warning them that their experience may be poor with IE6.

Step 1 is to determine the user’s browser when they hit your site.  On my web app’s login page, I use a simple conditional similar to the below example to display a formatted message to the user:

if(eregi('MSIE 6.0', $_SERVER['HTTP_USER_AGENT'])) {
    echo 'You are accessing this site using Internet Explorer 6.0.  We make every reasonable attempt to ensure this site is compatible with IE6, but due to the age and lack of web standards compliance in IE6, you may experience some errors and bugs that are beyond our control.  For best performance, we STRONGLY recommend a more modern browser, such as <a href="http://www.mozilla.org/firefox">Mozilla Firefox</a>, <a href="http://www.apple.com/safari/download">Apple Safari</a>, or <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Microsoft Internet Explorer 8</a>, which are all available for free.  Firefox and Safari are recommended for the best overall experience and performance, though Internet Explorer 7 and 8 are also fully compatible. Less than 7.5% of traffic on this site is from users on IE6.  Therefore, at some point we will make a decision not to support IE6 any longer, as it takes considerable effort to maintain this backward compatibility. PLEASE UPGRADE YOUR BROWSER SOON!';
}

Wrap that message with some bold styling to grab the user’s attention. Then start watching your browser traffic with Google Analytics.

Once IE9 is out of beta, I’ll change the message to include it in the recommended browsers, but for now I want to funnel my users into a browser with some CSS3 support, because I’ve incorporated a lot of it into my app and I think it improves the user experience a great deal.

What I’ve seen in the past few months is a steady reduction in IE6 traffic from the mid 30% range this time last year, to 10% a couple of months ago, down to 7.1% this past week. I believe the biggest reduction has been deployment of Win7 desktops, but the incremental drive from 10% down to current levels seems to be due to the above user warning.

The other thing I’ve been doing is verbally encouraging use of Firefox any time the issue comes up. When I get a call or email about a bug, if I can’t replicate it in Safari then it is almost always a browser specific issue, and when asked the user almost always informs me he or she is using IE6.

Once IE6 usage hits 5% I am going to change the warning message to say that IE6 is no longer supported. Of course I’ll continue to make accommodations, but I’m not going to go out of my way to make IE6 users comfortable in the application–it just doesn’t make sense any longer.

Learning PHP

Its quite possible you found this blog while googling around for information on PHP.  If that’s true, and you’re a newbie trying to learn PHP, I’d like to direct you over to a new post on Six Revisions entitled Learn PHP: Get Started Using PHP by Elias Zerrouq. After a brief history of the language, the article goes on to describe what PHP is, how it works, and the basic steps one must take to begin working with PHP, including installing and/or setting up a development environment, picking a source code editor, and writing your first few lines of code.

Coming Up: My First ZendCon

Thanks to a slight relaxation in departmental travel/education funds, I get to go to a conference this fiscal year.  I chose ZendCon, and I’m pretty excited about it.

Unless I find other folks from my institution that are also going, I’ll be “flying solo”…an introvert at a geek conference…should be interesting.

Anyway, I’ll try to resist my nature and make some new connections.  Mostly I’m just excited about the wide range of subjects and the potential to soak in as much of it as possible.  If you’re also headed to ZendCon, drop me a note.

iPhone 4 3G Reception Testing with iOS 4.0.1

I’ve stayed silent on the iPhone 4 antenna “debacle”, and I frankly think that although there is a legitimate issue at the heart, it has been overblown by a media eager to find a chink in Mr. Jobs’ armor.

Before I get too far into this let me just say I’ve become quite the Apple fan over the last three years and even stood in line for 7 hours outside the Apple Store on June 24th to pick up my iPhone 4.

I’ve been able to replicate the “Death Grip” bar loss on purpose, but I’ve yet to have it cost me a call either on accident or when purposefully trying to kill a call with it.

I just downloaded the new iOS 4.0.1 update with its modified signal bar algorhythm and decided to do some of my own testing. Granted this is not controlled testing and it is not terribly randomized, so take this test with a grain of salt, just like all other tests that you read on blogs.  I’m not even terribly confident that Consumer Reports’ testing was done in the proper environment.

Anyway, I have a generally good 3G signal at my house, owing mostly to being in the Nashville metropolitan area.  The test methodology was to conduct 5 tests using Speedtest.net app, take a photo of the 5th test in each phone position/mode, and then average the 5.  The positions/modes tested were: Wifi (a control), 3G-no hands (control), 3G w/2-fingers, 3G casual hold, and 3G Death Grip.  What follows are the results of the testing along with some pics. All speeds are in kbps.

Wifi

Methodology: Home Wifi network, Airport Extreme Base Station, Comcast Cable Modem, phone on desk, no hands.

Test Download Upload
1 3403 3073
2 3407 3196
3 3637 3178
4 3583 3089
5 3560 3129
Average 3518 3133
SDC10567

Wifi Test #5 (Yeah I know the bars have nothing to do with Wifi...)

3G No Hands

Methodology: 3G, phone on desk, no hands. Full 5 Bars.

Test Download Upload
1 890 897
2 1223 955
3 1351 1257
4 1322 1151
5 689 1273
Average 1095 1107
3G test #5, no hands, 5 Bars

3G test #5, no hands, 5 Bars

3G 2-Fingers

Methodology: 3G, phone on desk, Thumb and pointer finger tightly gripping, bridging antenna gaps on either side of phone. 2 Bars.

Test Download Upload
1 789 297
2 591 218
3 951 229
4 1399 203
5 1093 655
Average 963 320
3G 2-finger test #4, 2 bars

3G 2-finger test #4, 2 bars

3G Casual Hold

Methodology: 3G, phone in hand casually (not tight at all), like I’d be dialing or surfing the web. 3 Bars.

Test Download Upload
1 0 127
2 794 277
3 917 265
4 97 206
5 1119 136
Average 585 202
3G Causal Hold test #5, 3 Bars

3G Causal Hold test #5, 3 Bars

3G Death Grip

Methodology: 3G, phone in hand so tight it hurt my hand for a few minutes (see second photo below), like I’m an Apple-hater trying to score points on my blog. 1 Bar.

Test Download Upload
1 11 52
2 0 0
3 5 0
4 0 76
5 2 0
Average 3.6 25.6
3G Death Grip Test #5, 1 Bar

3G Death Grip Test #5, 1 Bar

My hand after 5 tests of the death grip

My hand after 5 tests of the death grip

Conclusions

Let’s just throw out the death grip completely.  Why?  Because I had to hold the phone so tightly it hurt, and no reasonable person is going to hold their phone that tightly to make a call or surf the web or do anything else one does with an iPhone.  Its not a realistic scenario that is likely to occur in the real world.

Having said that, the Casual Hold is entirely valid, and its results were hardly better.  While the average speeds for Casual Hold are way higher than for Death Grip, note the wild inconsistency among the tests in download speeds.  I’m curious to see if this variance continues if one were to conduct a couple dozen tests.  Whatever causes the inconsistency in a casual grip is probably why the problem seems so hard to reproduce for some folks (including me).

I think we can throw out the 2-finger test for the same reason we threw out the Death Grip, no body holds their phone this way. If you did, you’d drop it.  Its a nice way to demonstrate the flaw in a controlled and explicit way, but its not a realistic demonstration of the scenario that causes the problem in actual use.  Having said that, the results are similar to, but more consistent than the Casual Hold.

As for the 3G on the desk with no hands, those results speak for themselves. I won’t bother discussion the Wifi results, they are here just for comparison’s sake and validation of my methodology.

Overall the casual hold represents a 47% drop in download speed and a 72% drop in upload speed. That’s significant enough to notice, but the raw speed is still well above 2G speeds and fast enough one ought to be able to use the phone if in an area with a half-way decent signal to begin with.

I’d also like to note that in both Death Grip and Casual Hold positions I was still able to dial and complete calls.  So one might say looking at data speeds when the issue is call reception is comparing apples to oranges (pun intended). That is a valid criticism.

Clearly the exposed antennas are prone to some attenuation issues. Oddly this seems to only really affect the 3G antenna though.  So yes, its a flaw.  Is it fatal?  I don’t really think so.  And judging by the lack of long return lines at Apple stores and continuing high demand, I don’t think the majority of consumers are all that upset about this.

Are there folks who’s phones are virtually unuseable because of this flaw? Yes, I’m sure there are some, but its hardly approaching even a large minority of iPhone 4 buyers.  Is it a great number as a percent of the whole than had issues with previous models or would have issues with another brand of phone?  Who knows, nobody’s sought fit to actually find any real data, this whole thing seems to be one giant anecdotal evidence party.

The media and Apple-haters (is it hate or just jealousy?) are certainly enjoying the brief exposure of Apple’s soft underbelly. Apple has gone from counter culture chick to mainstream in just a couple of years.  As other articles have noted, though they are still barely 10% of the PC marketshare, they dominate the all important mindshare.  Everybody loves to hate the big kid on the block, be it Microsoft, Wal-Mart, or GM in years past.  Now that Apple is at the top of the heap and making busloads of money, they should get used to taking shots from the media, competitors and even perhaps formerly allied counter culture.

My guess on the press conference tomorrow is that Steve sends everyone who has already bought an iPhone 4 an Apple Store credit for $30 to be used on a bumper, which actually costs just a buck or two to make.  Some who don’t have a reception problem will end up spending the credit on something else, perhaps even a significantly higher priced item.  This remedy actually ends up making Apple more money, much to the chagrin of the Apple haters.  The white iPhones will be announced to have been delayed while a modification (a coating?) is made to the steel band, and future black models will receive the same modification.

MySQL Views just aren’t “there yet”….

I am a big fan of Jason Gilmore. His book Beginning PHP and MySQL (link is to latest version, not my actual copy) actually launched my developer career four years ago.

His latest post over on PHPbuilder.com, Refactor Your PHP Site Using MySQL Procedures and Views, has some good information about using views and stored procedures to simplify application logic and improve code maintainability.

I tried to comment to the article on PHPBuilder, but their comment deal is broken, so I thought this would make a decent blog post.

There is no question views and stored procedures are both powerful tools that MySQL went without for quite some time. However, I disagree with Jason to the extent his article fails to mention there is a cost to using these tools.

MySQL’s implementation of views has some well documented performance problems. I won’t go into them in detail here, you can read an excellent summary on the MySQL Performance Blog in a post by Peter called MySQL view as a performance troublemaker.  The urge to save yourself from writing a complex query can end up costing you and your users down the road when performance issues crop up.

In a vacuum, I completely agree that views and stored procedures should be an essential tool in the developer’s toolbox.
However, in reality, MySQL’s implementation of views leaves a lot to be desired.  MySQL views have a tremendous amount of overhead associated with them and using a PHP-side join query, no matter how complex, will result in significantly better performance than a MySQL view.
This article has much more to say on View performance in MySQL: http://www.mysqlperformanceblog.com/2007/08/12/mysql-view-as-performance-troublemaker/
I like stored procedures but as with views, PHP can often do many of these transformations and calculations more quickly than the MySQL server can.  I also think you have to be wary of putting too much stuff into stored procedures and creating a confusing architecture if not careful to  heed separation of concerns.

I like stored procedures, but SQL is slow when compared to PHP, and stored procedures will hit the database CPU more than a corresponding function in PHP.  I also think you have to be wary of putting too much stuff into stored procedures and creating a confusing architecture. A good developer always heeds the rule of separation of concerns.  Stuffing so much stuff into the database eventually will defeat the original purpose of simplifying code maintainability, particularly in a team environment.

If we’re talking Oracle or another of the more mature RDBMS products out there, there is no question that views should be leveraged as much as possible. While stored procedures are not as big of a performance concern, mis- or over-use can lead to architectural issues. With respect to views,  MySQL just isn’t there yet.

Never Use $_GET Again

Matt Butcher’s new blog entry, Never Use $_GET Again, discusses using the filter_input function that is available in php 5.2+ to remedy concerns about input validation.  Its an elegantly simple approach that solves a busload of problems.  This is worth reading and I think is going to not only be worth implementing but also worth retrofitting to your existing applications.

Toggle Table Rows with jQuery, no plug-in required

Last week I encountered a situation with one of our web apps that required a toggle-able table row. Essentially the existing table was populated with information from four different tables. In addition to several joins there were some nested queries, and it was killing the MySQL server.

So, I decided to pull the information from the nested queries out of the rows and use a hidden table row below each existing row where I would show the formerly nested information using an ajax call to retrieve. Removing the nested queries significantly improved query performance.

The biggest problem in this was creating a table row that toggles. The native toggle() jquery function didn’t work at first, and this is because a table row’s display attribute is “table-row”, and not “block” as toggle() resets to.

I found this jQuery plugin by Janko at Warp Speed for doing exactly what I need. It is simple and works quite well with the minimum necessary amount of code. This is accomplished by using jQuery calls to add an anonymous click function to the even rows. However, there are some drawbacks. First, if you observe the demo, notice that a click anywhere in the parent row triggers the toggle.  This is great unless you have a link in the parent row.  What to do if you have, say, a table of employees and you want a link to their full record in the parent row?

Quite unintentionally, after fiddling with jQuery for a couple of hours I came up with a solution.  Only after I tested did I realize I had Janko’s plugin commented out.  I was able to confirm my solution works with no plugin required.  Rather than using the odd/even selectors in jQuery, I have used row ID numbers as you will see in the demo.  To exempt the cell with the link from the anonymous click function, I have added the clickable class to each cell instead.  If you don’t want this extra layer of complexity, just strip out all the parent() business from the JavaScript.

Please help yourself to the code and let me know what you think. View the demo…

P.S. In case you are wondering why I have an empty third row for each record:  This is to preserve the jQuery-based alternating table row highlighting that uses the jQuery even selector.  Since Janko’s solution also relies on this method, it was wiping out my table striping.

Gerrymandered Code: Extending Zend_Registry to globalize session vars

In my most recent post I talked about putting my toes in the Zend Framework water with stand-alone usage of Zend_Cache. This has been a great experience, and since writing the post I’ve been updating my main application with more caching anywhere I can see a benefit.

In the past couple of days I waded a little deeper into ZF, installing Zend_Registry (also stand-alone) and using it to globalize configuration variables that I was previously loading into $_SESSION in order to access throughout my scripts and inside classes without having to pass them explicitly.

I’ve been using $_SESSION like this for a couple of years, and I’ve known the whole time it was a band-aid approach to solve the problem. Such an approach is not an ideal “design pattern.” Though it passes my baseline rule–it works–there are downsides. The two most obvious are that 1) there’s nothing to stop me from accidentally overwriting a session var inside some script or method, and 2) there’s no sense loading up the session handler with stuff that really shouldn’t be in there.

Zend_Registry is a very lightweight module (one file), that is actually an extension to the native ArrayObject PHP5 class. Any variable, object, or scalar you load into Zend_Registry instantly becomes available globally throughout your script. Let me prevent confusion by saying there is no persistence across page loads–this is just for within each request–but the upside is any scope issues are swept away in a very elegant manner. Hint: Combine Zend_Registry with Zend_Cache to achieve persistence.

The Registry design pattern is not unique to ZF, you can even write your own Registry class if you care to.  I’m still not fluent in OOP-speak, but I understand Zend_Registry is implemented by default as a Singleton.  I know there’s a lot of trashing of the Singleton pattern out there in programmer land.  However, I don’t get too hung up on such metaphysical debates…not to say there isn’t merit in the argument, but for me and my work it is not a practical concern.

I refactoring my main app with Zend_Registry in place of my rat’s nest of $_SESSION[‘config’][‘foo’] and such…which is mostly just things like email addresses for the system admin (me) and other global variables that may come in handy in any script or method.

As with my previous ZF article, I’ll leave the details to the fine folks at Zend (see Zend_Registry documentation here), but the implementation of Zend_Registry in this fashion can be exactly this simple:

Zend_Registry::set('admin_email', 'chris.renner@company.net ' );

And then later in your script (or function or object method or wherever) you return the value by calling:

Zend_Registry::get('admin_email' );

Wow, how elegant! You can also access the registry as an object or as an array. For my needs, the static setter/getter methods are perfect.

Netbeans’ Find and Replace features made it relatively simple to update my code with the new Zend_Registry calls.  I guess the “web developer” jargon for that would be “I refactored my code base.”

Problem solved, right?  Well yes and no.  The pesky need for globalized config vars has been solved, but there is a related problem.  How did I ever get the idea to store config variables in $_SESSION?  Probably the same way most of you reading this did in your newbie days:  I was already using $_SESSION to store actual, legitimate session variables at user login, and then access those variables through my code.

gerrymanderIn addition to being a code jockey, I am a politics junkee and also the owner of a second major in Political Science (I know, its so rare to find someone working in a field that is wholly unrelated to their degree…).  It occurred to me there is an analogy to be made between a  Gerrymandered congressional district and what the pros call “spaghetti code.”  I think my amateur-ish use of $_SESSION as a global band-aid amounts to what one might call “Gerrymandered code.”  I am hereby coining the phrase!

The obvious solution to replace all the $_SESSION tags littered throughout my code is to simply load $_SESSION into Zend Registry like so:

Zend_Registry::set('session', $_SESSION);

This works, but retrieving session vars proves to be a bit clunky. My reading of the ZF documentation suggests there isn’t a way to access the value of an array element in the Registry in a direct fashion. You therefore have to instantiate Zend_Registry every time you need access to a session var. For example…

$registry = new Zend_Registry();
echo $registry['session']['userID'];

I find this a bit clunky to do every time I need to access my session. I also don’t care for all the extra overhead caused by generating an object for each one of these cases.

My solution was to extend Zend_Registry with another class that can access an array element inside the registry and return it directly. Here’s what I came up with:

/**
 * A simple extension to Zend_Registry to allow direct access to array objects
 * and object properties inside the registry
 * @author Chris Renner http://www.chrisrenner.com
 */
class App_Registry extends Zend_Registry {
 
    /**
     * Constructs a parent Zend_Registry with default
     * ARRAY_AS_PROPS to allow access as an object
     *
     * @param array $array data array
     * @param integer $flags ArrayObject flags
     */
    public function __construct($array = array(), $flags = parent::ARRAY_AS_PROPS) {
        parent::__construct($array, $flags);
    }
 
    /**
     * getter method for directly accessing value of an array element stored in a registry index
     *
     * @param string $index - the array we're accessing
     * @param string $key - the element we want to access
     * @return mixed
     */
    public static function getFromArray($index, $key) {
 
        $array = self::get($index);
 
        if(is_object($array)) {
            $var = $array-&gt;$key;
        } elseif(is_array($array)) {
            $var = $array[$key];
        }
 
        return $var;
    }
 
    /**
     * setter method for directly modifying value of an array element stored in a registry index
     *
     * @param string $index - the array we're accessing
     * @param string $key - the element we want to access
     * @param string $val - the value we want to assign
     * @return mixed
     */
    public static function setInArray($index, $key, $val) {
 
        $registry = self::getInstance();
 
        if(is_object($registry[$index])) {
            $registry[$index]-&gt;$key = $val;
        } elseif(is_array($registry[$index])) {
            $registry[$index][$key] = $val;
        }
 
    }
 
}

As you can see, there are just two methods. getFromArray returns the value of an array element or object property from the registry. You just need to supply the Zend_Registry index and the key/property name you want back.

setInArray is used to update an existing property or array element. Supply the Zend_Registry index, the property/key name, and the value you want to assign.

So now, if I want to get the userID from the session (We still set the session array into the registry using Zend_Registry::set() as above), I can call a new static method like this:

echo App_Registry::getFromArray('session', 'userID');

…and to change the value I simply call this:

App_Registry::setInArray('session', 'userID', $newValue);

Obviously this is a very rough class.  It could use more polish, like error handling in case we’re trying to access something that is neither an object or an array.  This can be used to access elements/properties for any array or object you might pass into the registry (not just session vars).

You might ask why not just use constants to globalize config vars?  You certainly could in a simple application.  If you want to change those vars in the script or store an array, you’re out of luck.

I’m curious to see what readers of this post might think, if you have suggestions for improvements or better ways of doing the same thing.  Thanks for reading!