5
Develop rock-solid code in PHP: Lay the foundation, Part 1 Country/region [select] Terms of use Home Products Services & industry solutions Support & downloads My IBM developerWorks In this article: Lay a rock-solid foundation Design it right Write rock-solid code Secure your code Keep it simple Make it platform-independent Build for speed Summary Resources About the author Rate this page Related links Web development technical library Linux technical library developerWorks > Web development | Linux > Develop rock-solid code in PHP: Lay the foundation, Part 1 From 20,000 feet Document options Print this page E-mail this page Using XML, but need to do more? Download DB2 Express-C 9 Rate this page Help us improve this content Level: Intermediate Amol Hatwar ( [email protected]), Independent Consultant 01 Aug 2002 The Develop rock-solid code in PHP series is about solving practical real-life problems in medium- to large-scale applications. With a sharp focus on new features available in PHP 4, the articles shed light on numerous tips and tricks that make life easier. Inside, you will find plenty of examples and techniques to learn, with lots of sample code. In this first article, PHP veteran Amol Hatwar gives a higher perspective for designing and writing bug-free, maintainable code for medium- to large-scale Web applications. If you are a developer building Web applications and need speed, functionality, and platform-independence, then PHP is for you. Moreover it is free, easy to learn and deploy. These are the greatest strengths that makes PHP so popular. But these same strengths can also become weaknesses. Because of PHP's ease- of-use, developers often start by hammering code into their editors when they should have really been planning and designing. Also, you can solve a problem in more than one way in PHP and the dangers of making painful mistakes that become difficult to fix later are never far away. In this series of articles, you will learn how to avoid many mistakes. If you follow through faithfully, do not be surprised to find yourself writing bug-free code at the first or second attempt. I will also point out new features available in PHP 4 that make life easier. Most of the examples that I will cover deal with practical, real-life problems like script configuration and setup, file handling, and database usage. Even if you are new to all this, you should find it easy to follow. However, I will assume that you know elementary PHP. If you need to brush up, you will find the resources outlined at the end of this article helpful. (See Resources.) Lay a rock-solid foundation Coding in PHP is very much like coding in a language like C. They are syntactically similar which can also lead to similar code maintenance problems. When large-scale applications have to be developed, large quantities of code may be written. Over time, this code may become unmanageable and soon bugs creep in. Wherever you heard this, it is untrue -- at least partly. But the bigger truth is that if you find yourself maintaining your code too often, your application was probably poorly designed in the first place. Back to top Design it right The choices that you make initially affect your degrees of freedom when you code later. This makes proper design an important prerequisite. While design can become an extra ceremony when you are solving a trivial problem, you must at least acknowledge that this is the case. Many people think of design and planning as extra overhead. But starting with a bad design, or no design at all, always results in slip-shod code. Remember, no amount of clever coding can compensate for bad design. Although how to design applications is beyond the scope of this series of articles, I will suggest some issues that you should keep in mind when designing Web applications. Divide and conquer It is always preferable to design and code a big application in smaller loosely coupled parts. Then, each part stays maintainable. For example, a Content Management System (CMS) may be distributed over many smaller modules like user authentication, presentation, content parsing, and viewing statistics. And if your modules are generic enough, you can reuse your code in other applications that you develop. Programmers often do this and still complain. For coding, the trick is to let each module have the functionality it absolutely needs and stop there. Give a module nothing more and nothing less. Never think in pages http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (1 of 5)10/23/2006 11:53:36 PM

Develop rock-solid code in PHP: Lay the foundation, Part 1

Embed Size (px)

DESCRIPTION

The Develop rock-solid code in PHP series is about solving practical real-life problems in medium- to large-scale applications. With a sharp focus on new features available in PHP 4, the articles shed light on numerous tips and tricks that make life easier. Inside, you will find plenty of examples and techniques to learn, with lots of sample code. In this first article, PHP veteran Amol Hatwar gives a higher perspective for designing and writing bug-free, maintainable code for medium- to large-scale Web applications.

Citation preview

  • Develop rock-solid code in PHP: Lay the foundation, Part 1

    Country/region [select] Terms of use

    Home Products Services & industry solutions Support & downloads My IBM

    developerWorks

    In this article:Lay a rock-solid foundationDesign it rightWrite rock-solid codeSecure your codeKeep it simpleMake it platform-independentBuild for speedSummaryResourcesAbout the authorRate this page

    Related links

    Web development technical libraryLinux technical library

    developerWorks > Web development | Linux >

    Develop rock-solid code in PHP: Lay the foundation, Part 1From 20,000 feet

    Document options

    Print this page

    E-mail this page

    Using XML, but need to do more?

    Download DB2 Express-C

    9

    Rate this page

    Help us improve this content

    Level: Intermediate

    Amol Hatwar ([email protected]), Independent Consultant

    01 Aug 2002

    The Develop rock-solid code in PHP series is about solving practical real-life problems in medium- to large-scale applications. With a sharp focus on new features available in PHP 4, the articles shed light on numerous tips and tricks that make life easier. Inside, you will find plenty of examples and techniques to learn, with lots of sample code. In this first article, PHP veteran Amol Hatwar gives a higher perspective for designing and writing bug-free, maintainable code for medium- to large-scale Web applications.

    If you are a developer building Web applications and need speed, functionality, and platform-independence, then PHP is for you. Moreover it is free, easy to learn and deploy. These are the greatest strengths that makes PHP so popular. But these same strengths can also become weaknesses. Because of PHP's ease-of-use, developers often start by hammering code into their editors when they should have really been planning and designing. Also, you can solve a problem in more than one way in PHP and the dangers of making painful mistakes that become difficult to fix later are never far away.

    In this series of articles, you will learn how to avoid many mistakes. If you follow through faithfully, do not be surprised to find yourself writing bug-free code at the first or second attempt. I will also point out new features available in PHP 4 that make life easier. Most of the examples that I will cover deal with practical, real-life problems like script configuration and setup, file handling, and database usage. Even if you are new to all this, you should find it easy to follow. However, I will assume that you know elementary PHP. If you need to brush up, you will find the resources outlined at the end of this article helpful. (See Resources.)

    Lay a rock-solid foundation

    Coding in PHP is very much like coding in a language like C. They are syntactically similar which can also lead to similar code maintenance problems. When large-scale applications have to be developed, large quantities of code may be written. Over time, this code may become unmanageable and soon bugs creep in. Wherever you heard this, it is untrue -- at least partly. But the bigger truth is that if you find yourself maintaining your code too often, your application was probably poorly designed in the first place.

    Back to top

    Design it right

    The choices that you make initially affect your degrees of freedom when you code later. This makes proper design an important prerequisite. While design can become an extra ceremony when you are solving a trivial problem, you must at least acknowledge that this is the case. Many people think of design and planning as extra overhead. But starting with a bad design, or no design at all, always results in slip-shod code. Remember, no amount of clever coding can compensate for bad design. Although how to design applications is beyond the scope of this series of articles, I will suggest some issues that you should keep in mind when designing Web applications.

    Divide and conquer

    It is always preferable to design and code a big application in smaller loosely coupled parts. Then, each part stays maintainable. For example, a Content Management System (CMS) may be distributed over many smaller modules like user authentication, presentation, content parsing, and viewing statistics. And if your modules are generic enough, you can reuse your code in other applications that you develop. Programmers often do this and still complain. For coding, the trick is to let each module have the functionality it absolutely needs and stop there. Give a module nothing more and nothing less.

    Never think in pages

    http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (1 of 5)10/23/2006 11:53:36 PM

    http://www.ibm.com/http://www.ibm.com/developerworks/country/http://www.ibm.com/legal/http://www.ibm.com/http://www.ibm.com/products/http://www.ibm.com/servicessolutions/http://www.ibm.com/support/http://www.ibm.com/account/http://www.ibm.com/developerworkshttp://www.ibm.com/developerworks/views/web/library.jsphttp://www.ibm.com/developerworks/views/web/library.jsphttp://www.ibm.com/developerworks/views/linux/library.jsphttp://www.ibm.com/developerworks/http://www.ibm.com/developerworks/web/http://www.ibm.com/developerworks/linux/http://www.ibm.com/developerworks/javascript:print()javascript:void newWindow()http://www.ibm.com/developerworks/kickstart/database.html?S_TACT=105AGX01&S_CMP=SIMPLEARThttp://www.ibm.com/developerworks/kickstart/database.html?S_TACT=105AGX01&S_CMP=SIMPLEARTmailto:[email protected]?subject=Lay the foundation, Part 1
  • Develop rock-solid code in PHP: Lay the foundation, Part 1

    If you took interest in PHP to make your HTML pages more dynamic, this bit is for you. This habit generally starts when you want the date and time displayed on every page to make it look fresh. Every HTML page turns into a small PHP script with a skimpy line with the date function tucked in somewhere. If this is what one wants, one must agree that this is the simplest way of getting the job done. But just imagine what you will have to do to change the format of the date that appears on the page. You will have to change the code in every page.

    There are obviously better ways to do this. My favorite is to use a configuration file and define a constant in it that holds the format string for the date() function. You can then use the date() function wherever you need it. Every page will still end in a script, but you will have drastically minimized places where you must make a change to a single line of code.

    Figure 1. Avoid hard-wiring code

    As shown in Figure 1, a change in the date format will be visible on all the pages. The idea here is to avoid duplicating and hard-wiring code. Keep this in mind when writing large applications. When you avoid duplicating code, you make debugging and maintenance easier.

    Reduce client-side requirements

    The types of Web pages and applications have grown in many directions. First it was image and image maps, then Java applets and client-side scripts that did cool animations. Today it is Flash. It is good to have impact, but one must remember the whole idea behind the Web was to make information accessible to anyone who wanted it at any time. By employing technology that not all browsers and platforms support, you deny information to people. The person that could not access your Web site may have been your next customer!

    Your application design should minimize network traffic as much as possible. It is common to see sites that go over-the-top and give browsers an assortment of cookies just to work. Juggling a lot of cookies not only consumes bandwidth, but also makes things unmanageable. As a rule of thumb, if your application sends more than 40 KB of data or if your page requires more than 5 seconds to load, it is time to take the application back to the drawing board. Small tweaks here and there do not last for long. If you look around, the most popular and visited sites are very simple.

    You should also take into account the next wave of mobile devices and the connection they will use to access your application. As a best practice, your application must tailor content according to the client that is requesting it. As Leon Atkinson puts it in his book Core PHP Programming, page 720, "We can try to keep the size of the HTML documents small, and we can try to avoid complex HTML like nested tables, but we can't upgrade everyone's 28.8 modem".

    Separate code, content and presentation

    HTML is a markup language to present content and PHP is an HTML-embedded scripting language. This does make simple tasks easy -- take the date example, for instance. However, when you have complex requirements to implement, embedding PHP in HTML takes away simplicity from the code. Separating code, content, and presentation as much as possible is good. Consider this very document you are reading. This document was first created as an XML file. HTML and PDF versions were automatically generated using style sheets. The code (application that shows you this page), content (the XML document) and presentation (style sheets) are different.

    http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (2 of 5)10/23/2006 11:53:36 PM

  • Develop rock-solid code in PHP: Lay the foundation, Part 1

    Just as encapsulating core functionality in modules and avoiding code duplication is important, using a single source for content and presenting the content the way it is wanted on demand is also important. Your flexibility to tailor pages according to the client and connection speeds is increased. Another spin-off is that programmers, designers, and writers work independently of each other -- a good thing if you are handling a large project.

    Don't be afraid to scrap designs

    No matter what anyone tells you, application design is best learned by practice. If you are just getting started, you may make many mistakes -- that is how you learn. Bad designs deserve to be scrapped. That is why you must keep code, content, and presentation loosely coupled -- scrapping bad designs becomes a lesser pain. You can keep the content and the presentation while losing your older code to something better.

    Now, back to what I promised, making your code rock-solid. You must remember at all times that your code will power someone else's content and presentation. If your code is not up to it, no amount of spectacular efforts from other departments can make up for deficiencies.

    Back to top

    Write rock-solid code

    Given that the requirements of your code do not change, you should not find the need to change code significantly. Except for the occasional need for optimization and refinement, your code should run like a well-greased machine.

    Sounds difficult? It's not. Frankly put, writing rock-solid code doesn't require a genius. You just need to ask yourself the right questions when in doubt so that you don't stray off-track:

    Is it secure? Is it simple and comprehensible? Is it platform-independent? Is it fast enough?

    Back to top

    Secure your code

    Any system that caters to a large audience must be secure. Though PHP itself has been inert from attacks by black-hat hackers, one is never too certain. PHP 4 prior to version 4.2.2 had serious security flaws. Always make sure sensitive data are stored or transmitted on a network with proper encryption. This is more important for applications that transact business, store information like credit-card numbers, and transmit confidential data.

    Today, trusting data that users submit is difficult. Make sure that you validate it and ensure that it is clean before using it. Keep in mind that putting your Web application on the Internet exposes your system, your software, your data, and your business to a huge network.

    Ensure that your code runs securely at all times.

    Back to top

    Keep it simple

    Your code should be easily comprehensible, read well, and be well documented. To reduce the time needed to familiarize yourself with your own or others' code, maintain a common naming and coding convention throughout a project. Investing time to ensure these things pays off when the need to maintain code arises.

    Documenting code is better done while you are programming it. Tools are now available that can parse all your scripts and make neat looking documentation in HTML for you. If you change the behavior of the code, change the documentation accordingly. Having documentation about code that does undocumented things is of no real use.

    Ensure that your code is documented, simple, and easy to comprehend. It helps in the long run.

    Back to top

    Make it platform-independent

    Another issue that you must address is platform-independence. Of course, scripts written for PHP on Windows will work on PHP on any other platform: PHP is designed that way. However, you still need to take care of minor inconsistencies. The new line character, for instance, is represented differently in Windows and UNIX.

    You must also use abstraction when accessing resources like databases that are external to PHP. Say your application uses MySQL as a database server to cut costs. If you decide to have a more feature-rich database later, you will have to change the code in your application. Making massive changes to code is always a drudgery and an error-prone process. Using abstraction isolates changes to parts that can be easily changed. You do not have to redo the entire

    http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (3 of 5)10/23/2006 11:53:36 PM

  • Develop rock-solid code in PHP: Lay the foundation, Part 1

    application.

    Ensure that you write platform-independent code. It makes your application more adaptable and scalable.

    Back to top

    Build for speed

    The last factor worth tackling is speed. Nobody wants to wait forever as your script tediously selects 300 or so entries from a database and displays the results on a page. Putting 20 results on 15 different pages that travel and load quickly on the user's browser is always a better idea. The user perceives the faster response-time as speed. Another easy mistake is to create pages dynamically each time a user visits a page. This does ensure that your site stays fresh, but PHP isn't too forgiving when the number of users increases. You should cache frequently served pages. Caching makes your application faster and reduces the load on the server.

    Ensure that your code runs fast. Nobody likes waiting.

    Back to top

    Summary

    In this series opener, you saw what actually goes into making rock-solid code. Making big-applications in PHP is not at all difficult if you work carefully. In fact, many applications in PHP have been developed single-handedly. At the same time, it is important to realize that you can easily fall into traps. As long as you plan, break things down into smaller tasks, and implement them properly -- little else should get in your way.

    In the next installment, you will learn how to employ variables and functions efficiently. As a bonus, I will show you how to do some magic with variables and functions in PHP. We planned our flight in this article. We will get many more things in place after the next article -- perhaps even fly. Until then, bon voyage.

    Resources Visit phpbuilder.com for numerous beginner to intermediate level tutorials and resources.

    Push your skills further with the discussion groups, articles and many other tips at Zend, the company that

    makes PHP.

    Take the Developer Shed tutorial and learn to write self-documenting code in PHP.

    Try the PHPDocumentor tool, written in PHP, to extract documentation from your files.

    Explore the many beginner guides at Weberdev.com for information on using PHP in real-life.

    Just starting with PHP? Read "Introduction to PHP," a good place to start (developerWorks, December 2000).

    Learn the finer aspects of coding with PHP and MySQL in the article, "Creating dynamic Web sites with PHP and MySQL" (developerWorks, May 2001).

    Find out more on applying your new PHP skills in real-life with "Personalized Web sites in a jiffy" (developerWorks, September 2000).

    Check out Leon Atkinson's Core PHP Programming, a practical guide to PHP 4 for Web developers.

    About the author

    Amol Hatwar has been into computers for as long as he can remember. Being a GNU/Linux bigot, he feels guilty for spending his past-life programming on Microsoft platforms. He now works as an independent consultant helping companies migrate to GNU/Linux. A specialist in developing Web applications, he spends his mythical free-time dabbling with technologies no one has heard about. His current interests include open-source software, Web services, Peer-to-Peer computing, and high-availability clustering. You can contact Amol at [email protected].

    Rate this page

    http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (4 of 5)10/23/2006 11:53:36 PM

    http://www.phpbuilder.com/http://www.zend.com/http://www.devshed.com/Server_Side/PHP/SelfDoc/page1.htmlhttp://phpdocu.sourceforge.net/http://weberdev.com/http://www.ibm.com/developerworks/library/l-php.htmlhttps://www6.software.ibm.com/reg/devworks/dw-linuxphp-ihttps://www6.software.ibm.com/reg/devworks/dw-linuxphp-ihttp://www.ibm.com/developerworks/library/w-php/http://www.ibm.com/developerworks/library/w-php/http://www.amazon.com/exec/obidos/ASIN/013020787X/mailto:[email protected]?cc=
  • Develop rock-solid code in PHP: Lay the foundation, Part 1

    Please take a moment to complete this form to help us better serve you.

    Did the information help you to achieve your goal?

    Yes No Don't know

    Please provide us with comments to help improve this page:

    How useful is the information?

    1 2 3 4 5Not useful

    Extremely useful

    Back to top

    About IBM Privacy Contact

    http://www-128.ibm.com/developerworks/web/library/wa-phprock1/ (5 of 5)10/23/2006 11:53:37 PM

    http://www.ibm.com/ibm/http://www.ibm.com/privacy/http://www.ibm.com/contact/ibm.comDevelop rock-solid code in PHP: Lay the foundation, Part 1OLAKJMNLKKLECDNPKNJEKKIKPIEILMJM: form1: x: f1: 1f2: dWf3: [dW]f4: f5: form2: x: f1: 1f2: Develop rock-solid code in PHP: Lay the foundation, Part 1f3: Web development, Linuxf4: http://www.ibm.com/developerworks/thankyou/feedback-thankyou.htmlf5: 11231f6: 08012002f7: [email protected]: f9: http://www-128.ibm.com/developerworks/web/library/wa-phprock1/f10: Offf11: f12: Offf13: