Article

Getting Started with PEAR - PHP's Low Hanging Fruit

Page: 1 2 3

The Package Manager

OK, you've got this far. From now on, its gets a lot easier. The PEAR Package Manager should now be set up and ready to roll. To start with, from the command line, enter:

$ pear

Up should pop the basic usage of the PEAR Package Manager -- a list of possible subcommands you can use with it. You can change pretty much all the settings you specified when you installed PEAR. Enter the following:

$ pear config-show

Here you'll see the current configuration, with everything from the directories you specified when you installed it, to proxy server configuration and more. Generally, you shouldn't need to worry about these, but it's worth being aware how to control them. If you type:

$ pear config-help <optioname>

…you'll receive a short description of what that config option means. You can change your options using:

$ pear set <optioname>

Not impressed yet? All that work for what? Well, how about typing this...

$ pear install XML_Parser  
$ pear install XML_Util  
$ pear install XML_Serializer

The first line may have resulted in your being told it's already installed, depending on whether you accepted the recommended packages at install time. If so, just continue to the next line. What happens? There should have been some action, such as:

downloading XML_Serializer-0.9.1.tgz ...  
...done: 12,675 bytes  
install ok: XML_Serializer 0.9.1

What happened here? The PEAR Package Manager contacted the PEAR Website, found the latest version of XML_Serializer, downloaded it and installed it in your PEAR package library. You can immediately begin using the packages from your PHP scripts.

Impressed yet? The Package Manager is written in PHP, by the way. There's more to this language than meets the eye...

The PEAR Package Manager provides a number of mechanisms for installing PEAR packages. The first, which was used above, was XML-RPC. It "talks" to the PEAR Web server and finds out stuff like which release it should download.

It is also able to fetch and install directly using HTTP, downloading a package in much the same way as browser does. For example, if you wanted a specific version of HTML_QuickForm, such as 3.1.1, you can get the link to the file from the package homepage -- in this case, http://pear.php.net/get/HTML_QuickForm-3.1.1.tgz. You can then directly install it with:

$ pear install http://pear.php.net/get/HTML_QuickForm-3.1.1.tgz

You can also install files, which you've manually downloaded, from your local file system like so:

$ pear install /home/harryf/downloads/HTML_QuickForm-3.1.1.tgz

This also means that a package doesn't have to be on the PEAR Website (or part of PEAR at all) in order for you to use it. Other projects, such as the ISMO Framework, publish releases ready for the Package Manager (the .tgz files) and can be installed directly, using the same approach. If you had a library you wanted to make easier for people to install, you could do the same.

In attempting to install HTML_QuickForm, you may have encountered a problem: an error message saying it depends on HTML_Common. Some packages require other packages to be available. If you look at the HTML_QuickForm homepage, at the bottom, you'll notice it has a dependency on HTML_Common. That means HTML_Common will need to be installed first.

So, how does the PEAR package manager know what to do with a package? If you download some version of HTML_QuickForm, for example, with your browser and unzip it, you'll find a file in there called package.xml. This contains all the information about where the package's code should be placed, relative to your PEAR library directory. If you're ever really dead in the water and can't install the Package Manager, you could manually unzip a package and place it correctly in your include path, based on the information in package.xml (see a full description here). That's a last resort, though -- why make extra work for yourself?

Another useful command to know about is this one:

$ pear upgrade <package_name>

If you've already installed a package, that's how you upgrade to the newest version. Make sure you check the release notes first, in case the new version breaks your code.

One small "gotcha" when it comes to installing packages, is the "preferred_state" configuration setting. Currently, this can be set to "stable", "beta", "alpha", "devel" or "snapshot". Now, imagine you have the "preferred_state" set to "stable" (the default), and you typed:

pear install HTML_QuickForm

This would cause the Package Manager to install the newest stable version of the package. This means that, if there's a newer version of the package available, but the developers flagged it as, say, "beta", it will be ignored in preference of an older, stable release. It may mean, for packages that have never had a stable release, that the Package Manager will not let you install them unless you lower the preferred state.

Anyway, that's enough to get you started. As you can see, life is already a lot easier, thanks to PEAR.

Instant RSS

OK -- time to put my money where my mouth is. No doubt, you've already read Kev's article on PHP and XML: Parsing RSS 1.0. It explains the detail of building your own SAX handler for parsing RSS 1.0 and shows you how to fetch it from the SitePoint feed at http://www.sitepoint.com/rss.php.

Of course, it's a lot of work to write all that code for handling XML. Also, if you're trying to access the feed from behind a proxy server, you'll need some kind of HTTP client that's capable of understanding the headers the proxy server generates. PHP's fopen() function won't help you with that.

Thanks to PEAR, you can cut down the work involved in parsing an RSS feed significantly. Assuming you installed XML_Serializer up there, you also need PEAR::HTTP_Request. I'll leave it to you to install it and work out any issues with dependencies.

Once you have the required packages installed, use this code:

<?php  
// Include PEAR::HTTP_Request  
require_once 'HTTP/Request.php';  
 
// Include PEAR::XML_Unserializer  
require_once 'XML/Unserializer.php';  
 
// Create the HTTP_Request object, specifying the URL  
$Request = & new HTTP_Request('http://www.sitepoint.com/rss.php');  
 
// Set proxy server as necessary  
// $Request->setProxy('proxy.myisp.com', '8080', 'harryf', 'secret');  
 
// Send the request for the feed to the remote server  
$ErrorCheck = $Request->sendRequest();  
 
// Check for errors  
if ( PEAR::isError($ErrorCheck) ) {  
   die ( "Connection problem: ".$ErrorCheck->toString() );  
}  
 
// Check we got an HTTP 200 status code (if not there's a problem)  
if ( $Request->getResponseCode() != '200' ) {  
   die ( "Request failed: ".$Request->getResponseCode() );  
}  
 
// Get the body of the response - the XML document  
$xml = $Request->getResponseBody();  
 
// Create an instance of XML_Unserializer  
$UnSerializer = &new XML_Unserializer();  
 
// Unserialize the feed and dump the raw array  
if ( $UnSerializer->unserialize($xml) ) {  
   $feed = $UnSerializer->getUnserializedData();  
   echo "<pre>";  
   print_r ( $feed );  
   echo "</pre>";  
} else {  
   die ( "Error unserializing feed" );  
}  
?>

From a glance at the above example it's clear that there's much less code to deal with, yet, we enjoy more detailed error handling, thanks to PEAR::HTTP_Request having some "understanding" of the HTTP protocol. Also, you immediately get access to the data in the RSS feed (no need to think about XML). To finish off, it's just a matter of looping through the $feed["item"] array and displaying each row in HTML. I won't discuss the details of PEAR::HTTP_Request or XML_Serializer this time. The example is designed just to give you an idea of how PEAR can make your life easier.

Whether any given PEAR package will save you time depends on whether you know how to use it, of course, and with documentation often amiss that's often an issue. I strongly advise you research packages before planning them into a project (and that typically means looking at the source code).

Along those lines, you may be wondering why I didn't use PEAR::XML_RSS instead of XML_Serializer. After a glance at the source of XML_RSS, I noticed that it expects to be given file handle from which it can fetch the feed. That would have caused issues with HTTP_Request, which returns the response as a string. XML_RSS should suit many requirements, but in this instance, I needed something a little different.

Wrap Up

That should have given you enough of a taste of PEAR to get you started!

Personally, I think it's a great project and I'm finding myself taking advantage of PEAR packages more and more, whenever there's a good fit. Sure, not everything is perfect and there are occasions where you'll need to use hacks and workarounds to shape a package to what you need.

PEAR already has a lot to offer and is, by far, the largest combined PHP coding effort around. And as more and more PHP developers get behind PEAR, the better things will get.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: