XML配置文件
尽管文本文件易于阅读及编辑,但却不如 XML 文件流行。另外,XML 有众多适用的编辑器,这些编辑器能够理解标记、特殊符号转义等等。所以配置文件的 XML 版本会是什么样的呢?清单 11 显示了 XML 格式的配置文件。
清单 11. config.xml
<?xml version="1.0"?> <config> <Title>My App</Title> <TemplateDirectory>tempdir</TemplateDirectory> </config> |
<?php class Configuration { private $configFile = 'config.xml'; private $items = array(); function __construct() { $this->parse(); } function __get($id) { return $this->items[ $id ]; } function parse() { $doc = new DOMDocument(); $doc->load( $this->configFile ); $cn = $doc->getElementsByTagName( "config" ); $nodes = $cn->item(0)->getElementsByTagName( "*" ); foreach( $nodes as $node ) $this->items[ $node->nodeName ] = $node->nodeValue; } } $c = new Configuration(); echo( $c->TemplateDirectory."\n" ); ?> |
... function save() { $doc = new DOMDocument(); $doc->formatOutput = true; $r = $doc->createElement( "config" ); $doc->appendChild( $r ); foreach( $this->items as $k => $v ) { $kn = $doc->createElement( $k ); $kn->appendChild( $doc->createTextNode( $v ) ); $r->appendChild( $kn ); } copy( $this->configFile, $this->configFile.'.bak' ); $doc->save( $this->configFile ); } ... |
DROP TABLE IF EXISTS settings; CREATE TABLE settings ( id MEDIUMINT NOT NULL AUTO_INCREMENT, name TEXT, value TEXT, PRIMARY KEY ( id ) ); |
<?php require_once( 'DB.php' ); $dsn = 'MYsql://root:password@localhost/config'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } class Configuration { private $configFile = 'config.XML'; private $items = array(); function __construct() { $this->parse(); } function __get($id) { return $this->items[ $id ]; } function __set($id,$v) { global $db; $this->items[ $id ] = $v; $sth1 = $db->prepare( 'DELETE FROM settings WHERE name=?' ); $db->execute( $sth1, $id ); if (PEAR::isError($db)) { die($db->getMessage()); } $sth2 = $db->prepare('INSERT INTO settings ( id, name, value ) VALUES ( 0, ?, ? )' ); $db->execute( $sth2, array( $id, $v ) ); if (PEAR::isError($db)) { die($db->getMessage()); } } function parse() { global $db; $doc = new DOMDocument(); $doc->load( $this->configFile ); $cn = $doc->getElementsByTagName( "config" ); $nodes = $cn->item(0)->getElementsByTagName( "*" ); foreach( $nodes as $node ) $this->items[ $node->nodeName ] = $node->nodeValue; $res = $db->query( 'SELECT name,value FROM settings' ); if (PEAR::isError($db)) { die($db->getMessage()); } while( $res->fetchInto( $row ) ) { $this->items[ $row[0] ] = $row[1]; } } } $c = new Configuration(); echo( $c->TemplateDirectory."\n" ); $c->TemplateDirectory = 'new foo'; echo( $c->TemplateDirectory."\n" ); ?> |