PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

User Object
(
[group:DomainObject:private] => default
)
SpreadSheet Object
(
[group:DomainObject:private] => document
)


For the User class, not much clever needs to happen. The DomainObject constructor calls
getGroup(), and finds locally. In the case of SpreadSheet, though, the search begins at the invoked class,
SpreadSheet itself. It provides no implementation, so the getGroup() method in the Document class is
invoked. Before PHP 5.3 and late static binding, I would have been stuck with the self keyword here,
which would only look for getGroup() in the DomainObject class.


Handling Errors


Things go wrong. Files are misplaced, database servers are left uninitialized, URLs are changed, XML
files are mangled, permissions are poorly set, disk quotas are exceeded. The list goes on and on. In the
fight to anticipate every problem, a simple method can sometimes sink under the weight of its own
error-handling code.
Here is a simple Conf class that stores, retrieves, and sets data in an XML configuration file:


class Conf {
private $file;
private $xml;
private $lastmatch;


function __construct( $file ) {
$this->file = $file;
$this->xml = simplexml_load_file($file);
}


function write() {
file_put_contents( $this->file, $this->xml->asXML() );
}


function get( $str ) {
$matches = $this->xml->xpath("/conf/item[@name=\"$str\"]");
if ( count( $matches ) ) {
$this->lastmatch = $matches[0];
return (string)$matches[0];
}
return null;
}


function set( $key, $value ) {
if (! is_null( $this->get( $key ) ) ) {
$this->lastmatch[0]=$value;
return;

Free download pdf