Good programmers write solid code, while great programmers reuse the code of good program- mers. For PHP programmers, PEAR, the acronym for PHP Extension and Application Repository, is
one of the most effective means for finding and reusing solid PHP code. Inspired by Perl’s wildly popular CPAN (Comprehensive Perl Archive Network), the PEAR project was started in 1999 by noted PHP developer Stig Bakken, with the first stable release bundled with PHP version 4.3.0.
Formally defined, PEAR is a framework and distribution system for reusable PHP components
and presently offers more than 400 packages categorized under 37 different topics. Because PEAR contributions are carefully reviewed by the community before they’re accepted, code quality and adherence to PEAR’s standard development guidelines are assured. Furthermore, because many PEAR packages logically implement common tasks guaranteed to repeatedly occur no matter the type of application, taking advantage of this community-driven service will save you countless hours of programming time.
This chapter is devoted to a thorough discussion of PEAR, offering the following topics:
• A survey of several popular PEAR packages, intended to give you an idea of just how useful this repository can really be.
• An introduction to the PEAR Package Manager, which is a command-line program that offers a simple and efficient interface for performing tasks such as inspecting, adding, updating, and deleting packages, and browsing packages residing in the repository.
Popular PEAR Packages
The beauty of PEAR is that it presents an opportunity to easily distribute well-developed code capable of solving problems faced by almost all PHP developers. Some packages are so commonly used that they are installed by default. Others are suggested for installation by PEAR’s installer.
Preinstalled Packages
Several packages are so popular that the developers started automatically including them by default as of PHP version 4.0. A list of the currently included packages follows:
219
• Archive_Tar: The Archive_Tar package facilitates the management of tar files, providing methods for creating, listing, extracting, and adding to tar files. Additionally, it supports the Gzip and Bzip2 compression algorithms, provided the respective PHP extensions are installed. This package is required for PEAR to run properly.
• Console_Getopt: It’s possible to create PHP programs that execute from the command line, much like you might be doing with Perl or shell scripts. Often the behavior of these programs is tweaked. The Console_Getopt package provides a standard means for reading these options and providing the user with error messages if the supplied syntax does not correspond to some predefined specifications (such as whether a particular argument requires a parameter). This package is required for PEAR to run properly.
• PEAR: This package is required for PEAR to run properly.
Installer-Suggested Packages
If you run the PEAR installer (even if PEAR is already installed), you’ll be asked whether you’d like to also install seven additional packages. A description of each package follows. We suggest opting to install all of them, as all are quite useful:
• Mail: Writing a portable PHP application that is capable of sending e-mail may be trickier than you think because not all operating systems offer the same facilities for supporting this feature. For instance, by default, PHP’s mail() function relies on the sendmail program (or a sendmail wrapper), but sendmail isn’t available on Windows. To account for this incompati- bility, it’s possible to alternatively specify the address of an SMTP server and send mail through it. However, how would your application be able to determine which method is available? The Mail package resolves this dilemma by offering a unified interface for sending mail that doesn’t involve modifying PHP’s configuration. It supports three different back ends for sending e-mail from a PHP application (PHP’s mail() function, sendmail, and an SMTP server) and includes a method for validating e-mail address syntax. Using a simple application configu- ration file or Web-based preferences form, users can specify the methodology that best suits their needs.
• MDB2: The MDB2 package provides an object-oriented query API for abstracting communica- tion with the database layer. This affords you the convenience of transparently migrating applications from one database to another, potentially as easily as modifying a single line of code. At present there are nine supported databases, including FrontBase, InterBase, Microsoft SQL Server, MySQL, MySQLi, Oracle 7/8/9/XE, PostgreSQL, and SQLite. Because the MDB2 project is a merge of two previously existing projects, namely DB and Metabase, and DB has support for dBase, Informix, MiniSQL, ODBC, and Sybase, one would imagine support for these databases will soon be added to MDB2, although at the time of writing nothing had been announced. MDB2 also supports query simulations using the QuerySim approach.
• Net_Socket: The Net_Socket package is used to simplify the management of TCP sockets by offering a generic API for carrying out connections and reading and writing information between these sockets.
• Net_SMTP: The Net_SMTP package offers an implementation of SMTP, making it easy for you to carry out tasks such as connecting to and disconnecting from SMTP servers, performing SMTP authentication, identifying senders, and sending mail.
• PHPUnit: A unit test is a particular testing methodology for ensuring the proper operation of a block (or unit) of code, typically classes or function libraries. The PHPUnit package facilitates the creation, maintenance, and execution of unit tests by specifying a general set of structural guidelines and a means for automating testing.
• XML_Parser: The XML_Parser package offers an easy object-oriented solution for parsing
XML files.
If you haven’t yet started taking advantage of PEAR, it’s likely you’ve spent significant effort and time repeatedly implementing some of these features. However, this is just a smattering of what’s available; take some time to peruse http://pear.php.net/ for more solutions.
The Power of PEAR: Converting Numeral Formats The power of PEAR is best demonstrated with a specific example. In particular, we call attention to a package that exemplifies why you should regularly look to the repository before attempting to resolve any significant programming task.
Suppose you were recently hired to create a new Web site 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 on the Web site must appear in this format. Take a moment to think about this require- ment because fulfilling 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 that the site copyright year in the page footer is always up to date? You’re just about to settle in for a long evening of coding when you pause for a moment to consider whether somebody else has encountered a similar problem. “No way,” you mutter, but taking a quick moment to search PEAR certainly would be worth the trouble. You navigate over and, sure enough, encounter Numbers_Roman.
For the purpose of this exercise, assume that the Numbers_Roman package has been installed on the server. Don’t worry too much about this right now because 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? By using the following script:
<?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 2007, this script would produce the following:
Copyright © MMVII
The moral of this story? Even though you may think that a particular problem is obscure, other programmers likely have faced a similar problem, and if you’re fortunate enough, a solution is readily available and yours for the taking.
Installing and Updating PEAR
PEAR has become such an important aspect of efficient PHP programming that a stable release has been included with the distribution since version 4.3.0. Therefore, if you’re running this version or later, feel free to jump ahead and review the section “Updating Pear.” If you’re running PHP version 4.2.X or earlier, in this section you’ll learn how to install the PEAR Package Manager on both the Unix and Windows platforms. Because many readers run Web sites on a shared hosting provider, this section also explains how to take advantage of PEAR without running the Package Manager.
Installing PEAR
Installing PEAR on both Unix and Windows is a trivial matter, done by executing a single script. Instructions for both operating systems are provided in the following two subsections.
Installing PEAR on Linux
Installing PEAR on a Linux server is a rather simple process, done by retrieving a script from the http://go-pear.org/ Web site and executing it with the PHP binary. Open up a terminal and execute the following command:
%>lynx -source http://go-pear.org/ | php
Note that you need to have the Lynx Web browser installed, a rather standard program on the Unix platform. If you don’t have it, search the appropriate program repository for your particular OS distribution; it’s guaranteed to be there. Alternatively, you can just use a standard Web browser such as Firefox and navigate to the preceding URL, save the retrieved page, and execute it using the binary.
If you’re running PHP 5.1 or greater, note that PEAR was upgraded with version 5.1. The improve- ments are transparent for users of previous versions, however, the installation process has changed very slightly: %>lynx -source http://pear.php.net/go-pear.phar | php.
No matter the version, once the installation process begins, you’ll be prompted to confirm a few
configuration settings such as the location of the PHP root directory and executable. You’ll likely
be able to accept the default answers (provided between square brackets that appear alongside the prompts) without issue. During this round of questions, you will also be prompted as to whether the six optional default packages should be installed. It’s presently an all-or-none proposition; therefore, if you’d like to immediately begin using any of the packages, just go ahead and accede to the request.
Installing PEAR on Windows
PEAR is not installed by default with the Windows distribution. To install it, you need to run the go-pear.bat file, located in the PHP distribution’s root directory. This file installs the PEAR command, the necessary support files, and the aforementioned six PEAR packages. Initiate the installation process by changing to the PHP root directory and executing go-pear.bat, like so:
%>go-pear.bat
You’ll be prompted to confirm a few configuration settings such as the location of the PHP root directory and executable; you’ll likely be able to accept the default answers without issue. During this round of questions, you will also be prompted as to whether the six optional default packages should be installed. It’s presently an all-or-none proposition; therefore, if you’d like to immediately begin
using any of the packages, just go ahead and accede to the request.
■Note While the PEAR upgrade as of version 5.1. necessitates a slight change to the installation process on Unix/
Linux systems, no change is necessary for Windows, although PHP 5.1’s Windows port also includes the upgrade.
For the sake of convenience, you should also append the PHP installation directory path to the
PATH environment variable so the PEAR command can be easily executed.
At the conclusion of the installation process, a registry file named PEAR_ENV.reg is created. Executing this file will create environment variables for a number of PEAR-specific variables. Although not critical, adding these variables to the system path affords you the convenience of executing the PEAR Package
Manager from any location while at the Windows command prompt.
■Caution Executing the PEAR_ENV.reg file will modify your system registry. Although this particular modifica-
tion is innocuous, you should nonetheless consider backing up your registry before executing the script. To do so, go to Start ➤ Run, execute regedit, and then export the registry via File ➤ Export.
PEAR and Hosting Companies
If your hosting company doesn’t allow users to install new software on its servers, don’t fret because it likely already offers at least rudimentary support for the most prominent packages. If PEAR support is not readily obvious, contact customer support and inquire as to whether they would consider making
a particular package available for use on the server. If they deny your request to make the package available to all users, it’s still possible to use the desired package, although you’ll have to install it by a somewhat more manual mechanism. This process is outlined in the later section “Installing a PEAR Package.”
Updating PEAR
Although it’s been around for years, the PEAR Package Manager is constantly the focus of ongoing enhancements. That said, you’ll want to occasionally check for updates to the system. Doing so is a trivial process on both the Unix and Windows platforms; just execute the installation process anew. This will restart the installation process, overwriting the previously installed Package Manager version.
Using the PEAR Package Manager
The PEAR Package Manager 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 get better acquainted with the Package Manager, open up a command prompt and execute the following:
%>pear
You’ll be greeted with a list of commands and some usage information. This output is pretty long, so it won’t be reproduced here. Instead you’ll be introduced to just the most commonly used commands. If you’re interested in learning more about one of the commands not covered in the remainder of this chapter, execute that command in the Package Manager, supplying the help parameter like so:
%>pear help <command>
■Tip If PEAR doesn’t execute because the command is not found, you need to add the executable directory to
your system path.
Viewing an Installed PEAR Package
Viewing the packages installed on your machine is simple; just execute the following:
%>pear list
Here’s some sample output:
Installed packages:
===================
Package Version State
Archive_Tar 1.3.1 stable
Console_Getopt 1.2 stable
HTML_AJAX 0.4.0 alpha
Mail 1.1.10 stable
Net_SMTP 1.2.8 stable
Net_Socket 1.0.6 stable
XML_Parser 1.2.7 stable
XML_RPC 1.2.2 stable
Learning More About an Installed PEAR Package
The output in the preceding section indicates that nine packages are installed on the server in ques- tion. However, this information is quite rudimentary and really doesn’t provide anything more than the package name and version. To learn more about a package, execute the info command, passing it the package name. For example, you would execute the following command to learn more about the Console_Getopt package:
%>pear info Console_Getopt
Here’s an example of output from this command:
ABOUT CONSOLE_GETOPT-1.2
========================
Provides Classes: Console_Getopt
Package Console_Getopt
Summary Command-line option parser
Description This is a PHP implementation of "getopt" supporting both short and long options.
Maintainers Andrei Zmievski <andrei@php.net> (lead) Stig Bakken <stig@php.net> (developer)
Version 1.2
Release Date 2003-12-11
Release License PHP License
Release State stable
Release Notes Fix to preserve BC with 1.0 and allow correct behaviour for new users
Last Installed Version - None -
Last Modified 2005-01-23
As you can see, this output offers some very useful information about the package.
Installing a PEAR Package
Installing a PEAR package is a surprisingly automated process, accomplished simply by executing the install command. The general syntax follows:
%>pear install [options] package
Suppose for example that you want to install the Auth package. The command and corresponding output follows:
%>pear install Auth
Did not download dependencies: pear/File_Passwd, pear/Net_POP3, pear/MDB,pear/MDB2, pear/Auth_RADIUS, pear/Crypt_CHAP,pear/File_SMBPasswd, use --alldeps or --onlyreqdeps to download automatically
pear/Auth can optionally use package "pear/File_Passwd" (version >= 0.9.5)
pear/Auth can optionally use package "pear/Net_POP3" (version >= 1.3)
pear/Auth can optionally use package "pear/MDB"
pear/Auth can optionally use package "pear/MDB2" (version >= 2.0.0RC1)
pear/Auth can optionally use package "pear/Auth_RADIUS"
pear/Auth can optionally use package "pear/Crypt_CHAP" (version >= 1.0.0)
pear/Auth can optionally use package "pear/File_SMBPasswd" pear/Auth can optionally use PHP extension "imap"
pear/Auth can optionally use PHP extension "vpopmail" downloading Auth-1.3.0.tgz ...
Starting to download Auth-1.3.0.tgz (39,759 bytes)
..........done: 39,759 bytes
install ok: channel://pear.php.net/Auth-1.3.0
As you can see from this example, many packages also present a list of optional dependencies that if installed will expand the available features. For example, installing the File_SMBPasswd package enhances Auth’s capabilities, enabling it to authenticate against a Samba server. Enabling PHP’s IMAP extension allows Auth to authenticate against an IMAP server.
Assuming a successful installation, you’re ready to begin using the package.
Automatically Installing All Dependencies
Later versions of PEAR will install any required package dependencies by default. However you might also wish to install optional dependencies. To do so, pass along the -a (or --alldeps) option:
%>pear install -a Auth_HTTP
Manually Installing a Package from the PEAR Web Site
By default, the PEAR Package Manager installs the latest stable package version. But what if you were interested in installing a previous package release, or were unable to use the Package Manager alto- gether due to administration restrictions placed on a shared server? Navigate to the PEAR Web site at http://pear.php.net/ and locate the desired package. If you know the package name, you can take a shortcut by entering the package name at the conclusion of the URL: http://pear.php.net/ package/.
Next, click the Download tab found toward the top of the package’s home page. Doing so produces
a linked list of the current package and all previous packages released. Select and download the appropriate package to your server. These packages are stored in TGZ (tar and Gzip) format.
Next, extract the files to an appropriate location. It doesn’t really matter where, although in most cases you should be consistent and place all packages in the same tree. If you’re taking this installation route because of the need to install a previous version, it makes sense to place the files in their appropriate location within the PEAR directory structure found in the PHP root installation directory. If you’re forced to take this route in order to circumvent ISP restrictions, creating a PEAR directory in your home directory will suffice. Regardless, be sure this directory is in the include_path.
The package should now be ready for use, so move on to the next section to learn how this is accomplished.
Including a Package Within Your Scripts
Using an installed PEAR package is simple. All you need to do is make the package contents available to your script with include or preferably require. Keep in mind that you need to add the PEAR base directory to your include_path directive; otherwise, an error similar to the following will occur:
Fatal error: Class 'MDB2' not found in /home/www/htdocs/book/11/database.php on line 3
Those of you with particularly keen eyes might have noticed that in the earlier example involving the Numbers_Roman package, a directory was also referenced:
require_once("Numbers/Roman.php");
A directory is referenced because the Numbers_Roman package falls under the Numbers category, meaning that, for purposes of organization, a corresponding hierarchy will be created, with Roman.php placed in a directory named Numbers. You can determine the package’s location in the hierarchy simply by looking at the package name. Each underscore is indicative of another level in the hierarchy, so in the case of Numbers_Roman, it’s Numbers/Roman.php. In the case of MDB2, it’s just MDB2.php.
■Note See Chapter 2 for more information about the include_path directive.
Upgrading Packages
All PEAR packages must be actively maintained, and most are in a regular state of development. That said, to take advantage of the latest enhancements and bug fixes, you should regularly check whether a new package version is available. You can upgrade a specific package, or all packages at once.
Upgrading a Single Package
The general syntax for upgrading a single package looks like this:
%>pear upgrade [package name]
For instance, on occasion you’ll want to upgrade the PEAR package, responsible for managing your package environment. This is accomplished with the following command:
%>pear upgrade pear
If your version of a package corresponds with the latest release, you’ll see a message that looks like the following:
Package 'PEAR-1.4.9' already installed, skipping
If for some reason you have a version that’s greater than the version found in the PEAR reposi- tory (e.g., you manually downloaded a package from the package author’s Web site before it was
officially updated in PEAR), you’ll see a message that looks like this:
Package 'PEAR' version '1.4.9' is installed and 1.4.9 is > requested '1.4.8', skipping
Otherwise, the upgrade should automatically proceed. When completed, you’ll see a message that looks like the following:
downloading PEAR-1.4.10.tgz ...
Starting to download PEAR-1.4.10.tgz (106,079 bytes)
........................done: 106,079 bytes upgrade ok: PEAR 1.4.10
Upgrading All Packages
It stands to reason that you’ll want to upgrade all packages residing on your server, so why not perform this task in a single step? This is easily accomplished with the upgrade-all command, executed like this:
%>pear upgrade-all
Although unlikely, it’s possible some future package version could be incompatible with previous releases. That said, using this command isn’t recommended unless you’re well aware of the conse- quences surrounding the upgrade of each package.
Uninstalling a Package
If you have finished experimenting with a PEAR package, have decided to use another solution, or have no more use for the package, you should uninstall it from the system. Doing so is trivial using the uninstall command. The general syntax follows:
%>pear uninstall [options] package name
For example, to uninstall the Numbers_Roman package, execute the following command:
%>pear uninstall Numbers_Roman
If other packages are dependent upon the one you’re trying to uninstall, a list of dependencies will be output and uninstallation will fail. While you could force uninstallation by supplying the
-n (--nodeps) option, it’s not recommended because the dependent packages will fail to continue working correctly. Therefore, you should uninstall the dependent packages first. To speed the uninstallation process, you can place them all on the same line, like so:
%>pear uninstall package1 package2 packageN
Downgrading a Package
There is no readily available means for downgrading a package via the Package Manager. To do so, download the desired version via the PEAR Web site (http://pear.php.net/), which will be encapsulated in TGZ format, uninstall the presently installed package, and then install the downloaded package using the instructions provided in the earlier section “Installing a PEAR Package.”
Summary
PEAR can be a major catalyst for quickly creating PHP applications. Hopefully this chapter convinced you of the serious time savings this repository can present. You learned about the PEAR Package Manager and how to manage and use packages.
Later chapters introduce additional packages, as appropriate, showing you how they can really speed development and enhance your application’s capabilities.
Tuesday, July 14, 2009
Beginning PHP and Oracle From Novice to Professional by W. Jason Gilmore and Bob Bryla Chapter 11
Posted by Mr Procces at 9:25 AM
Labels: Oracle, PHP, Web Applications, Web Development
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment