Did you know that you can obtain PEAR packages via Composer? And you don't need to install or set up PEAR or configure global settings!
A work colleague was talking about difficulties setting up CPAN for Perl on a server and that got me thinking about dependency managers and repositories and the options available in the PHP world. The modern way to manage dependencies and find libraries/packages is using Composer and Packagist but the old way was through using PEAR which was a global dependency manager with a repository of useful packages. I started to wonder if it was possible to load an old-style PEAR package through the new Composer dependency manager and after some fiddling about I got it working successfully.
Not long ago the PEAR guys decided to create a new version of PEAR so there are now two PEAR repositories available: classic PEAR (http://pear.php.net) and PEAR2 (http://pear2.php.net) which is also known as Pyrus. Most of the packages are still stuck in the old PEAR repository. So let's pick a test package from each of them to install. For PEAR2 I'm going to try the package suggested in the Composer documentation, PEAR2_HTTP_Request, and for old PEAR I'm going to try Numbers_Roman.
Open up the composer.json file and edit it so it looks something like this:
{
"repositories": [
{
"type": "pear",
"url": "http://pear.php.net"
},
{
"type": "pear",
"url": "http://pear2.php.net"
}
],
"require": {
"pear-pear2/PEAR2_HTTP_Request": "*",
"pear-pear/Numbers_Roman": "*"
}
}
The two different PEAR repositories are defined in the repositories section of the composer.json file. Note the first two words (pear-pear and pear-pear2) used in the paths of the require values. This allows Composer to know which repository to look in. Details about choosing alternative channels are in the Composer documentation.
Then run php composer.phar update to install the new packages.
Now we can create a new PHP file to test the packages just installed. Here's my test code. Note that PEAR2 packages are namespaced, hence the use command:
<?php
require 'vendor/autoload.php';
use pear2\HTTP\Request,
pear2\HTTP\Request\Adapter\Curl;
$url = 'http://www.yahoo.com/';
$request = new Request($url, new Curl());
$response = $request->sendRequest();
$nr = new Numbers_Roman();
//http response code 200 or 'CC' in roman numerals means success
if ('CC' == $nr->toNumeral($response->code)) {
echo "Successfully accessed $url";
} else {
echo "An error (HTTP{$response->code}) occured while trying to access $url";
}
?>
And that's it. Composer is just awesome!
No comments:
Post a Comment