PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 15 ■ AN INTRODUCTION TO PEAR AND PYRUS

relevant channels have been discovered before running channel-discover with the -o (optional
dependencies) flag set.


Using a PEAR Package


Once you have installed a PEAR package, you should be able to use it in your projects immediately. Your
PEAR directory should already be in your include path—there should be no problem including the
package once it has been installed. Let’s install PEAR_Config and any dependencies it might have:


$ pear install -a Config
downloading Config-1.10.11.tgz ...
Starting to download Config-1.10.11.tgz (27,718 bytes)
.........done: 27,718 bytes
downloading XML_Parser-1.2.8.tgz ...
Starting to download XML_Parser-1.2.8.tgz (13,476 bytes)
...done: 13,476 bytes
install ok: channel://pear.php.net/Config-1.10.11
install ok: channel://pear.php.net/XML_Parser-1.2.8


Here’s how you would include the package:

require_once("Config.php");


class MyConfig {
private $rootObj;


function __construct( $filename=null, $type='xml' ) {
$this->type=$type;
$conf = new Config();
if (! is_null( $filename ) ) {
$this->rootObj = $conf->parseConfig($filename, $type);
} else {
$this->rootObj = new Config_Container( 'section', 'config' );
$conf->setroot($this->rootObj);
}
}


function set( $secname, $key, $val ) {
$section=$this->getOrCreate( $this->rootObj, $secname );
$directive=$this->getOrCreate( $section, $key, $val );
$directive->setContent( $val );
}


private function getOrCreate( Config_Container $cont, $name, $value=null ) {
$itemtype=is_null( $value )?'section':'directive';
if ( $child = $cont->searchPath( array($name) ) ) {
return $child;
}
return $cont->createItem( $itemtype, $name, null );
}


function __toString() {
return $this->rootObj->toString( $this->type );

Free download pdf