Why PHP Frameworks Matter

Why PHP Frameworks Matter

Editor’s Note: This is a guest essay from W. Jason Gilmore, a PHP developer and bestselling author with more than ten years of professional experience. He’s the author of the popular new book, “Easy PHP Websites with the Zend Framework”, which includes access to almost five hours of online video, a periodically updated e-book, and access to a reader-restricted online forum. You can buy the book through both Amazon.com and EasyPHPWebsites.com.

In a 1998 interview with Dr. Dobb’s Magazine, creator of the Perl programming language Larry Wall concluded his answer to the final question with a tip I’ve never forgotten, remarking, “Take a good look at what you want to do, and try to come up with the long-term lazy way, not the short-term lazy way.” [1] To paraphrase another Larry Wall-ism, in the programming world “laziness is indeed a virtue”, and if you’re not a lazy programmer, then frankly you’re not trying hard enough.

Having been a PHP programmer for more than a decade, I’ve come to realize that many of my fellow PHP programmers seem to have a misplaced notion of what being “lazy” is really all about. I know that because until just a few years ago I suffered from the very same delusion. You see, PHP has a funny effect on programmers. It’s just so darned easy to use, and has so many readily available native capabilities that it’s easy to fall into the trap of believing you can rely on an amassed set of custom code libraries, tips, and tricks learned over the years in the trenches. Which is precisely what I did until about 2005, when programming suddenly got hard. In many ways 2005 was a watershed year for the Web, with among other things Jesse James Garrett setting the development world afire with the first formalized definition of Ajax [2], Google releasing the first version of its now ubiquitous mapping API, RSS really began to enter the mainstream, and a little-known company named Facebook began to receive serious venture capital infusions.

Suddenly the Web developer was facing so much more than validating user input and connecting to a database. Users began clamoring for rich interactive experiences made possible through a complex blend of JavaScript, CSS, HTML, and server-side languages. They’ve come to take for granted the ability to access Web site data through third party outlets such as RSS, and Google Gadgets. They want to use PayPal to purchase your products, and wouldn’t mind knowing whether any of their Facebook friends are also regular users of your site.

Suddenly the need to be a lazy programmer was more important than ever.

Enter the PHP Framework

With all of these new responsibilities being placed on the developer, it isn’t by accident that 2005 also happened to be the year in which all three of PHP’s major Web frameworks were born. The first public versions of CakePHP, symfony, and the Zend Framework all hit the Web, with another popular framework named CodeIgniter following soon thereafter with its first release in early 2006. With each seeking to lessen the burden on developers by abstracting away many of the programmatic tasks which always seem to rear their ugly head no matter the project type or scale.

Using a framework, developers are able to forego decisions such as where to place configuration information, how to go about validating user input, and whether to store user session information in a file or database. Also gone are the need to mix the Web site’s logic, page templates, and database-related code, because the conventions enforced by the framework go a long way towards making the separation a natural part of the development process.

Although I’ve used all of the aforementioned frameworks to varying degrees, I’m most familiar with the Zend Framework (insomuch that I wrote a book on the topic), and so thought I’d devote the remainder of this essay to several Zend Framework-related examples which illustrate just how much these solutions have to offer. Hopefully, these examples will be enough to convince those of you not already using a framework to learn more about one of these fantastic solutions.

Staging Features and Configuration Consolidation

When developing a Web site, you’ll typically be working with three versions: a development version hosted either on your laptop or on a local office server, a beta version which has been deployed to a hosting environment identical to that used for the third version, namely the production version which is made available to your audience. To compound this problem of version juggling, you’ll often use different configuration parameters for each version. For instance, if you’re using a database, then you’ll likely have different connection credentials for each site version. You’ll also want to suppress the display of errors within your production version, but make sure all errors are prominently reported on the development version.

To help you manage these versions, each Zend Framework-powered Web site uses a configuration file named application.ini, a sample of which is displayed below. You’ll see that in the section titled [production, PHP’s error reporting is disabled, and the timezone is set to PDT, because the production server is hosted on the West coast. In the [development] section, error reporting is enabled, and the timezone is set to EDT because my test server is located in Columbus, Ohio. In both sections you’ll also find database-specific connection parameters.

To migrate between versions, all you need to do is change a single setting in an .htaccessfile which determines the Web site version each server should be using.

Data Validation

Anyone who has built even a simple Web site knows how painful data validation can be. But it’s a necessary evil; if you don’t validate user input, it’s only a matter of time before your Web site data is stolen, deleted, or otherwise changed in a way that can be harmful to other users. Because of the importance of this task, the Zend Framework developers have taken great pains to create a powerful data validation feature capable of parsing even the most complex strings.

A great example of these capabilities involves validation of an e-mail address. Because of all of the possible variations, regular expression syntax used to validate an e-mail address can be extremely complex. For instance, here’s one way to do it:

That’s not a pretty sight. Thanks to the Zend Framework, validating an e-mail address is as simple as this:

Database Operations

I’m not afraid to say it; I hate SQL, and a shiver runs down my spine every time I see SQL statements and PHP code mixed together. Mixing two languages together in this fashion has never seemed natural, and so the Zend Framework’s database abstraction capabilities is undoubtedly my favorite feature.

Using this feature, you communicate with the database tables using an object-oriented interface, completely removing the need to write SQL statements. Here’s a simple example which should nonetheless really demonstrate the power of this feature. Suppose you built a Web site which stored information about your favorite video games. The table schema looks like this:

Retrieving all rows of this table within your Zend Framework-powered Web site is as simple as this:

Within the corresponding page you can loop through the $this->view->games array as you would any other:

The Zend Framework offers many advanced database features which allow you to account for table relations, create joins, and much more.

Display Helpers

When building the Web site’s interface, you’ll often create programmatically-driven visual representations of data which might appear within several different places on the site. Using a Zend Framework view helper, you can greatly reduce the amount of code and effort required to build these features. For instance, we can create a view helper which converts an integer value used to represent the number of stars a visitor has assigned a game when writing a review of the game into a string of star icons which considerably improve the page’s design, as shown in Figure 1.

Figure 1. Creating a starred review Figure 1. Creating a starred review

This view helper is packaged into an object-oriented class, and looks something like this:

With this view helper now available to your Web site, you can call the helper as necessary within your layout, as demonstrated here:

Let’s break down some code:

  • Line 12 defines the location of the star icon. This icon happens to be part of the spectacular FAMFAMFAM Mini icon set. Of course, for organizational reasons you might consider storing the image path in the config.ini file.
  • Lines 15-18 cycle through the for loop a number of times equivalent to the value of the $rating input parameter. Each time it loops, another tag containing the star.png path will be appended to the $stars variable.
  • Line 19 returns the $stars variable to the calling view.

I think this is an ideal example of the power of view helpers because such a small amount of code adds so much to the Web site.

Third-party Plugins

I’d like to conclude this essay with some mention of the Zend Framework’s third-party capabilities. Rather than present any code, I thought I’d instead just enumerate a few of my favorite plugin features built directly into the default framework download. Click on any of the accompanying links to learn more about what these powerful features can do for you:

  • Zend_Service_Amazon: Plugs into Amazon’s Product Advertising API
  • Zend_Service_Flickr: Plugs into the Flickr photo sharing service
  • Zend_OpenId: Plugs into Google’s Authentication, Book, Docs, Health, Apps, Search, and YouTube services
  • Zend_OpenId: Plugs into the OpenID identity provision framework

Conclusion

With all of these features at your fingertips, what’s stopping you from getting lazy and building something great? I hope you enjoyed this essay, and invite you to contact me with your questions at [email protected].

To help give you a further head start into PHP frameworks, we’ll be launching a giveaway of Jason’s latest book towards the end of this week. This post is a great sample of what you can find in the book, so be sure to check back later for your chance to scoop a copy up!

Footnotes

[1] “A Conversation with Larry Wall”, Dr. Dobb’s Magazine. February 1, 2998. http://www.ddj.com/windows/184410483

[2] “Ajax: A New Approach to Web Applications”, Adaptive Path. February 18, 2005. http://adaptivepath.com/ideas/essays/archives/000385.php

Posted Tuesday, August 11th, 2009 · Back to Top

SPONSOR

Add Comment

30 Comments 9 Mentions

  1. Eric B. Author Editor

    Huh. I was just thinking about PHP framworks earlier today, and then I saw this post in my RSS reader!
    .-= Eric B.´s last blog ..Creating a PHP CMS – Part 1 =-.

    ·

  2. Rasmus Author Editor

    Very interesting. Thanks! I’ve never tried any PHP Framework yet. Any usersuggestions on where and wich to begin with?

    ·

  3. MorayWeb Author Editor

    I have been having fun with CodeIgniter for a number of months now, I don’t think I’ll go back to non framework based development. I know that any app that I develop will have consistant security, structure and scalability that would be near impossible (if not very time consuming) in a ground up coded project.

    I went through a big decision process as to which framework to use, that ultimately tore me between Zend and CodeIgniter. For all I am using CodeIgniter exclusively just now I may well have another look at Zend as a result of this article.

    Great post, thanks!
    .-= MorayWeb´s last blog ..A Bit Of An Update! =-.

    ·

  4. Mark Author Editor

    On the other end of the Scale Rasmus Lerdorf (Original author of the PHP) is completely against php frameworks as shown in this post. http://www.sitepoint.com/blogs/2008/08/29/rasmus-lerdorf-php-frameworks-think-again/

    “how poor they are at performance. Not only are they slow, but their “jack-of-all-trades” attitude leads developers down the wrong path by not using what is best for the job. ”

    Just some food for thought.
    .-= Mark´s last blog ..The Summer =-.

    ·

  5. web2000 Author Editor

    Your article arrived to my attention right on time for something i am working on.. thanks!
    .-= web2000´s last blog ..50 unique search engines – that are not Google – Part2 =-.

    ·

  6. mary Author Editor

    Nice article Jason. I’m now starting to learn Zend and while it has a little bit of a learning curve, it definitely looks like this is the direction I’ll be taking in all my dev work. While using straight up PHP is simpler and more suitable for some small projects and scripts, using a framework like Zend opens up more possibilities and allows easy scaling.

    Thanks again for the excellent post.
    .-= mary´s last blog ..Building a Website With MODx for Newbies – Part 11: Adding Comments with Jot =-.

    ·

  7. Andy Walpole Author Editor

    Would you recommend a framework for learners through? Wouldn’t it be best if they aimed to create their own code of library first? Okay, so it probably won’t be as sharp as that what would be found in the frameworks you mentioned above, but at least they would become familiar with the all aspects of the code.
    .-= Andy Walpole´s last blog ..Using the Right Drupal Modules to Stop Troublesome Users and Spam =-.

    ·

  8. czechspekk Author Editor

    Hi, nice article tho. Explains the most important points why usage of frameworks makes developer’s life lazier = easier =more productive. On current project I’m working on, we use Zend as well, and from technical point it’s actually good choice. On one hand it provides basic mvc infrastructure and on the other hand enough of ‘Developer’s freedom’ – how & where u put your code. With the latest version now available, cli tools brings another level of development pace. That can be called huge leap for the ZF. I’ve been using Symfony last 3 years for almost all needed projects so I really appreciate cli in Zend now. Enough of oda. ZF is not fullstack framework, what I feel is more feature than a problem, but in some terms it’s loosing some score. It’s definigely the best library of php classes u can get, but then it’s just up to your skills how u can manage it. And belive me I saw completely non MVC project written in Zend, just because the dev had a choice how to do it and the drv had almost no knowledge of mvc pattern at all. So in this case usage of more strict framework e.g Symfony, prevents the codebase from junior mistakes and provides easier maintanance in longterm. Cheers R

    ·

  9. Asher Author Editor

    If you’re interested in the the frameworks mentioned above, I would also check out NOLOH (Not One Line of HTML) http://www.noloh.com, which is an easy, intuitive, lightweight and on-demand PHP framework that in many respects goes further than the few listed here.

    ·

  10. SeanJA Author Editor

    Good post, but I still think that method of validation is not lazy enough… this is better :P

    $validation['var'] = ‘max:50|min:6|email’;
    $this->validate($validation);
    $errors = $this->getValidationErrors();

    Also, I think you might have the wrong title on that second last link. It should be gData
    .-= SeanJA´s last blog ..Daily Digest for August 10th =-.

    ·

  11. Bruno Correia Author Editor

    Jason,
    I usually work on small projects and I would have used PDO statements and PHP filter ( FILTER_VALIDATE_EMAIL ) to accomplish these tasks above.

    My question is:
    Is it worth to learn and implement frameworks when dealing with small and mid size projects?

    Please let me know, I would appreciate your professional opinion.

    Thanks!

    ·

  12. Mini0n Author Editor

    CodeIgniter FTW!

    ·

  13. Sean Nieuwoudt Author Editor

    KohanaPHP is a fantastic framework too – http://kohanaphp.com/

    ·

  14. Khan Author Editor

    PHP Framework matters and every PHP developer needs to find one that works for them. Only when you have experience of using a PHP Framework you will really know when to use it or avoid it.

    Many developers get over whelmed by the size of options PHP Frameworks offer and decide that they are better off without it. Developers need to use a PHP Framework so that really know its weaknesses and strengths in able to make wise decision.

    Thanks for the post.
    .-= Khan´s last blog ..Really Useful Classes And Libraries For PHP Developers =-.

    ·

  15. Khairul Author Editor

    @mark You may want to try to take a look at Rasmus Lerdorf’s Keynote at Drupalcon 2008 regarding PHP Frameworks.

    http://szeged2008.drupalcon.org/program/sessions/rasmus-lerdorf-keynote-simple-hard
    .-= Khairul´s last blog ..Think a little, code a little.. =-.

    ·

  16. Mohamed Ben Dhaou Author Editor

    I am more a CodeIgniter guy, didn’t have much time to try others in real work.
    .-= Mohamed Ben Dhaou´s last blog ..12 jQuery Slideshow And Image Gallery Plugins And Scripts =-.

    ·

  17. Jason Gilmore Author Editor

    Hi everybody,

    Very interesting comments all!

    @Andy Walpole: As is typical in the PHP community, you’re certainly not lacking in choices. Obviously I’m biased (I like the Zend Framework so much that I wrote a book on the topic), however truth be told you’re going to have something to gain simply by trying any of them. All of the mainstream solutions are pretty well documented, so consider checking out their respective quickstart tutorials to get a feel for what’s involved. For instance, here’s the Zend Framework quickstart: http://framework.zend.com/docs/quickstart. By at least reading through the quickstarts, you may be able to get a feel for what’s involved and choose one based on your initial preference.

    @Bruno: I guess this depends upon your definition of a small project. If it’s simply creating a Web form which collects information and sends it to an email address, then using a simple PHP script makes the most sense. However, even if I were to create say a simple “online brochure” site for a small business, personally I’d use a framework simply because it removes *all* of the thinking regarding: where to place the javascript and CSS scripts, where to organize the layout, and how to query the database. By removing these issues from my thought process, I can concentrate on what really matters, which is creating a cool Web site.

    @Mark, @Khairul: Obviously Lerdorf’s opinions are to be taken into great consideration, and I suggest everybody checks out what he has to say on the topic. However I still think there’s plenty of opportunities for developers to take great advantage of frameworks for all of the reasons I cite above. As for the matter of performance, all of the projects seem to be improving in this regards all the time.

    Jason

    ·

  18. Opaw Author Editor

    1. $gameTable = new Zend_Db_Table(‘games’);
    2. $this->view->games = $gameTable->fetchAll();

    fetchAll()? What if your table contains millions of records or even just 50,000?
    That would be a disaster.
    Such function is not applicable on a high traffic sites which had a volume of records in the database.

    ·

  19. Ace Web Design Adelaide Author Editor

    Agreed that the benefits of a php framework are enormous, especially after you familiarise yourself with it.
    Opaw : You can fetachAll with limits, theres built in pagination and lots more.

    ·

  20. Opaw Author Editor

    Ace: What about I want to join 2 or 3 tables to get a results? Can we pass 2 or 3 tables to this function Zend_Db_Table()?
    If not then it’s not flexible.

    ·

  21. http://www.bendesign.eu Author Editor

    Nice article. PHP Framework matters and every PHP developer needs to find one that works for them. Thank you.

    ·

  22. Ivan Jovanovic Author Editor

    I’ve been using different frameworks during my professional PHP development career. CakePHP, codeIgnite, ZendFramework …
    In general, using frameworks can give a team more power and make them able to not reinvent the wheel every time and to code while “standing on the shoulders of giants”. From the other side, this also is a treat to the development of knowledge base in the team. As much as you use a framework, you become unaware of the problems that are solved by the components of the framework. You start looking of that as abstract layer too far from the underlying principles that are masked by the framework implementation. That way, team becomes less flexible with superficial knowledge of the nature of the problem that is solved by the frameworks. Especially when junior developer starts within the team and start working with framework before knowing the underlying layers.
    My suggestion is to use frameworks, wherever you find that it is reasonable that it will get you some value, but always look through the frameworks and try to learn true problems of web development problem domain. That way you will be able to compare how different frameworks solve same problems (as they all do), and eventually write your own framework that will be the perfect match for your particular problem, better than relying on some general purpose solution. Again if the value of writing it is reasonable.

    Cheers,
    Ivan
    .-= Ivan Jovanovic´s last blog ..echo "Happy Birthday"; =-.

    ·

  23. David Mach Author Editor

    For everyone who need develop a complex/business application (like a CRM, ERP or accounting) I strongly recommend the Symfony framework (http://www.symfony-project.org). In contrast to other frameworks (incl. Zend) this is full-stack framework with features from enterprise world. With excellent documentation is Symfony right choice!

    ·

  24. kalif Author Editor

    Nice article thannnnnnnnks
    .-= kalif´s last blog ..ÍÞíÈÉ ÇáßÊÑæäíÉ áÃÓÇÊÐÉ ÇáÓäÉ ÇáËÇäíÉ åäÏÓÉ ãíßÇäíßíÉ =-.

    ·

  25. marky Author Editor

    I love the KohanaPHP framework. It’s light and you can extend it nicely.

    As for Noloh, the idea seems interesting, but the fact that you need Javascript and Cookies enabled to run it breaks it for me. In my opinion, a website should be usable in plain HTML, then better with a CSS look, then add Javascript for the interface to make it even easier to use.

    Going to http://www.noloh.com without Javascript or Cookies illustrates the problem. This is a simple page with a menu and text. There is no reason it would require Javascript or Cookies. Furthermore, the Javascript on this page doesn’t help navigation, it makes it poorer. I need to hit more just to see a bit more text. It would have been much better designed if I could just read it all from the get go, and faster.

    Just my 2 cents.

    ·

  26. Vijay Joshi Author Editor

    I agree that frameworks do matter. Not only they cut down development time but also take care of things like data sanitation, database abstraction etc.
    My advice is try and choose a framework that suits your taste and then stick with it.

    ·

  27. Nicholas Author Editor

    Now i know the reason, thank you for sharing.

    ·

  28. ERP Author Editor

    ERP (Enterprise Resource Planning) is one of the most renowned and trusted software for growth of business worldwide, ERP gives your organization better visibility to control over what is going on in your business. The ERP enables you and your people to make business decisions with greater confidence.

    ·

  29. Hary Author Editor

    This is great information and very helpful. Thanks

    ·

  30. Keyworks: Wholesale Nike Shoes Author Editor

    Do you mind if I quote a few of your articles as long as I provide credit and sources
    back to your weblog? My website is in the very same niche
    as yours and my visitors would definitely benefit from some of the information you present here.
    Please let me know if this ok with you. Regards!

    ·

 

Build Internet by One Mighty Roar. Since 2008.