05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13 CHAPTER 13<br />

Application Techniques<br />

By now, you should have a solid understanding of the details of the <strong>PHP</strong> language and<br />

its use in a variety of common situations. Now we’re going to show you some techniques<br />

that you may find useful in your <strong>PHP</strong> applications, such as code libraries, templating<br />

systems, efficient output handling, error handling, and performance tuning.<br />

Code Libraries<br />

As you’ve seen, <strong>PHP</strong> ships with numerous extension libraries that combine useful<br />

functionality into distinct packages that you can access from your scripts. In previous<br />

chapters, we’ve covered using the GD, pdflib, and Sablotron extension libraries,<br />

and Appendix B lists all of the available extensions.<br />

In addition to using the extensions that ship with <strong>PHP</strong>, you can create libraries of<br />

your own code that you can use in more than one part of your web site. The general<br />

technique is to store a collection of related functions in a file, typically with a .inc file<br />

extension. Then, when you need to use that functionality in a page, you can use<br />

require_once( ) to insert the contents of the file into your current script.<br />

For example, say you have a collection of functions that help create HTML form elements<br />

in valid HTML—one function creates a text field or a textarea (depending on<br />

how many characters you tell it the maximum is), another creates a series of pop-ups<br />

from which to set a date and time, and so on. Rather than copying the code into<br />

many pages, which is tedious, error-prone, and makes it difficult to fix any bugs<br />

found in the functions, creating a function library is the sensible choice.<br />

When you are combining functions into a code library, you should be careful to<br />

maintain a balance between grouping related functions and including functions that<br />

are not often used. When you include a code library in a page, all of the functions in<br />

that library are parsed, whether you use them all or not. <strong>PHP</strong>’s parser is quick, but<br />

not parsing a function is even faster. At the same time, you don’t want to split your<br />

functions over too many libraries, so that you have to include lots of files in each<br />

page, because file access is slow.<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

297

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!