Taking Advantage of PEAR
All programmers know that code reuse is the key to an efficient and timely, not to mention sane, application development process. Yet far too few practice what is so often preached, much to the chagrin of colleagues, clients, and project managers everywhere. Such irrationality is compounded by the fact that many languages enjoy hyperactive user communities, who regularly churn out large amounts of code and make it available for others to freely adapt to their own needs.
PHP users have a particularly useful trove of code at their disposal, made available through the PHP Extension and Application Repository, better known as PEAR (http://pear.php.net/). Containing over 400 packages categorized under 40 different topics, and growing all the time, taking advantage of this community-driven service will save you countless hours of programming time. PEAR packages are available for accomplishing everything from creating barcode images, compressing files, abstracting database access, documenting code, and much more. In this article, I'll show you how to begin taking advantage of PEAR by introducing the PEAR Package Manager, and then demonstrating two useful packages.
PEAR has become such an important aspect of efficient PHP programming that it's been included with the distribution since version 4.3.0. I'll assume you're using this version or greater; if not, you'll need to install PEAR or upgrade to a later PHP version. See the PEAR manual for more information about the installation procedure.
You interact with PEAR using the PEAR Package Manager. It allows you to browse and search the contributions, view recent releases, and download packages. It executes via the command-line, using the following syntax:
%>pear [options] command [command-options] <parameters>
To start getting better acquainted with the manager, open up a command prompt and execute:
%>pearExecuting this command will produce a list of supported commands and usage information. Most users will only regularly use a subset of these commands, most notably:
- info: Display information about an installed package
- install: Install a package
- list: List installed packages
- list-all: List all packages found in the repository
- list-upgrades: List all available upgrades
- search: Search the repository
- uninstall: Uninstall a package
- upgrade: Upgrade a package
- upgrade-all: Upgrade all installed packages
Converting Numeral Formats with Numbers_Roman
To demonstrate the power of PEAR, I'd like to call attention to a package that I think exemplifies why you should regularly look to the repository before attempting to resolve any significant programming task. While some might consider this particular choice of package a tad odd, I'd like to call attention to it because the package both solves a particularly tricky problem, and is representative of a problem many would think few uncommon, and therefore not bother to search for an available solution. The package is Numbers_Roman, and makes converting Arabic numerals to Roman and vice versa a snap.
Suppose you were recently hired to create a new website for a movie producer. As we all know, any serious producer uses Roman numerals to represent years, and the product manager tells you that any date found on the website must appear in this format. Take a moment to think about this, as it isn't as easy as it may sound. Of course, you could look up a conversion table online and hard code the values, but how would you ensure the site copyright year in the page footer was always up to date? You're just about to settle in on a long evening of coding when you pause for a moment to consider whether somebody else has encountered a similar problem. Certainly taking a quick moment to search PEAR would be worth the trouble? You navigate over and sure enough, encounter Numbers_Roman.
For the purposes of this exercise, I'll assume the package has been installed on the server. Don't worry too much about this right now; you'll learn how to install packages in the next section. So how would you go about making sure the current year is displayed in the footer?
<?php // Make the Numbers_Roman package available require_once("Numbers/Roman.php"); // Retrieve current year $year = date("Y"); // Convert year to Roman numerals $romanyear = Numbers_Roman::toNumeral($year); // Output the copyright statement echo "Copyright © $romanyear"; ?>
For the year 2005, this script would produce:
Copyright © MMV
The moral of this story? Even though you may think the problem may be obscure, its almost a given that other programmers have faced a similar problem, and if you're fortunate enough, a solution is readily available and yours for the taking.
Creating HTML Forms
Creating HTML forms in an orderly manner can be tedious, particularly when the need arises to populate the form with dynamic data, for instance that retrieved from a database. Most developers choose to escape in and out of PHP code, outputting the dynamic data at the appropriate locations. While this works, the code can become quite messy. What if there was a more effective way? A quick review of PEAR turns up HTML_Quickform, and it makes forms creation trivial, not to mention data validation. Go ahead and install HTML_Quickform, passing the -a option to the install command in order to make sure all necessary dependencies are also installed.
For the first example, let's just create a simple form consisting of input fields for the user's name and email address:
<?php // Require HTML_QuickForm require_once 'HTML/QuickForm.php'; // Instantiate new object $form = new HTML_QuickForm('userprofile', 'post', 'formprocess.php'); // Add text field for the name $form->addElement('text', 'name', 'Name:', array('size' => 20, 'maxlength' => 50)); // Add text field for the email address $form->addElement('text', 'email', 'Email:', array('size' => 20, 'maxlength' => 50)); // Add a submit button $form->addElement('submit', null, 'Submit'); // Display the form $form->display(); ?>Executing this script produces the following form:
What if you wanted to auto-populate the form with some data retrieved from a database? Just create an associative array using keys that match the form element names, and then call the setDefaults() method prior to rendering the form. The modified script follows, with the new lines highlighted in bold:
<?php // Load the main class require_once 'HTML/QuickForm.php'; $userinfo = array("name" => "Jason Gilmore", "email" => "wjATATwjgilmore.com"); // Instantiate the HTML_QuickForm object $form = new HTML_QuickForm('userprofile', 'post', 'formprocess.php'); $form->addElement('text', 'name', 'Name:', array('size' => 20, 'maxlength' => 50)); $form->addElement('text', 'email', 'Email:', array('size' => 20, 'maxlength' => 50)); $form->addElement('submit', null, 'Update'); $form->setDefaults($userinfo); $form->display(); ?>
Executing this script produces:
This is just a glancing introduction to HTML_QuickForm, and is intended to give you an idea of the powerful packages available to you by way of PEAR. Take some time to peruse the package directory located at http://pear.php.net, I'm positive you'll be impressed at what you find!
About the Author
W. Jason Gilmore (http://www.wjgilmore.com/) is an open source editor for Apress. He's the author of the best-selling Beginning PHP 5 and MySQL: Novice to Professional (Apress, 2004. 748pp.). His writings on open source technologies have been featured within many of the computing industry's leading publications, including Linux Magazine, O'Reillynet, Devshed, and Zend.com. Jason loves receiving e-mail; so don't hesitate to write him at wjATwjgilmore.com.