PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS


will then be passed along to other Expression objects. So that data can be retrieved easily from the
InterpreterContext, the Expression base class implements a getKey() method that returns a unique
handle. Let’s see how this works in practice with an implementation of Expression:


abstract class Expression {
private static $keycount=0;
private $key;
abstract function interpret( InterpreterContext $context );


function getKey() {
if (! asset( $this->key ) ) {
self::$keycount++;
$this->key=self::$keycount;
}
return $this->key;
}
}


class LiteralExpression extends Expression {
private $value;


function __construct( $value ) {
$this->value = $value;
}


function interpret( InterpreterContext $context ) {
$context->replace( $this, $this->value );
}
}


class InterpreterContext {
private $expressionstore = array();


function replace( Expression $exp, $value ) {
$this->expressionstore[$exp->getKey()] = $value;
}


function lookup( Expression $exp ) {
return $this->expressionstore[$exp->getKey()];
}
}


$context = new InterpreterContext();
$literal = new LiteralExpression( 'four');
$literal->interpret( $context );
print $context->lookup( $literal ). "\n";


Here’s the output:

four

Free download pdf