Thursday, November 20, 2008

fluent expressions and conditionals

One problem I have encountered when designing "dsl" fluent expressions in php is conditionals.

If you are chaining methods and you have a method a which could fail and thus affect method b it is best to execute them independently and check the validity with an if clause before calling method b.


class Chain{
var $valid;
var $__methods;
var $__class_name;

function __construct(){
$this->valid = true;
$this->__class_name = get_class($this);
$this->__methods = get_class_methods($this->__class_name);
}

function __get($arg){
if(in_array($arg,$this->__methods)){
return $this->$arg();
}
}

function __call($arg,$data){
if(!$this->valid){
return $this;
}
$arg = '__'.$arg;
if(in_array($arg,$this->__methods)){
return call_user_func_array(Array($this,$arg),$data);
}
}

function __if($arg){
$this->valid = $arg;
return $this;
}

function __method1($value){
echo $value."\n";
return $this;
}

function start(){
$this->valid = true;
return $this;
}

function stop(){
$this->valid = false;
return $this;
}
}

function chain(){
$new = new Chain();
return $new;
}
chain()->if(false)->method1('will not display');

$x = 10;
chain()->if($x == 10)
->stop
->method1('wont work')
->if(false)
->start
->method1('will not work - will now')
->if(false)
->method1('will not work either');

No comments: