PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 11 ■ PERFORMING AND REPRESENTING TASKS

I’ll begin with the InterpreterContext class. As you can see, it is really only a front end for an
associative array, $expressionstore, which I use to hold data. The replace() method accepts an
Expression object as key and a value of any type, and adds the pair to $expressionstore. It also provides
a lookup() method for retrieving data.
The Expression class defines the abstract interpret() method and a concrete getKey() method that
uses a static counter value to generate, store, and return an identifier.
This method is used by InterpreterContext::lookup() and InterpreterContext::replace() to index
data.
The LiteralExpression class defines a constructor that accepts a value argument. The interpret()
method requires a InterpreterContext object. I simply call replace(), using getKey() to define the key
for retrieval and the $value property. This will become a familiar pattern as you examine the other
expression classes. The interpret() method always inscribes its results upon the InterpreterContext
object.
I include some client code as well, instantiating both an InterpreterContext object and a
LiteralExpression object (with a value of "four"). I pass the InterpreterContext object to
LiteralExpression::interpret(). The interpret() method stores the key/value pair in
InterpreterContext, from where I retrieve the value by calling lookup().
Here’s the remaining terminal class. VariableExpression is a little more complicated:


class VariableExpression extends Expression {
private $name;
private $val;


function __construct( $name, $val=null ) {
$this->name = $name;
$this->val = $val;
}


function interpret( InterpreterContext $context ) {
if (! is_null( $this->val ) ) {
$context->replace( $this, $this->val );
$this->val = null;
}
}


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


function getKey() {
return $this->name;
}
}
$context = new InterpreterContext();
$myvar = new VariableExpression( 'input', 'four');
$myvar->interpret( $context );
print $context->lookup( $myvar ). "\n";
// output: four


$newvar = new VariableExpression( 'input' );
$newvar->interpret( $context );
print $context->lookup( $newvar ). "\n";
// output: four

Free download pdf