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.)
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.
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.
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.
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.
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".
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.
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.
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.
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?
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.
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.
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 application.
Ensure that you write platform-independent code. It makes your application more adaptable and scalable.
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.
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.
- 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.
- 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.
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 firstname.lastname@example.org.