What is the best approach to achieve this (probably using some design pattern )?
Let say we have 3 stages to process a user input, at each stage data is validated/transformed and if successful next step is executed. Proceeding to next step is not desired if previous step fails.
class PipeAndFilter
{
protected $input;
protected $proceedToNextStep;
public function __construct(Array $input)
{
$this->input=$input;
$this->proceedToNextStep=true;
}
public function process()
{
$this->filterOne();
if(!$this->proceedToNextStep()) return false;
$this->filterTwo();
if(!$this->proceedToNextStep()) return false;
$this>filterThree()
return $this->proceedToNextStep();
}
protected function filterOne()
{
//perform some action and set
//$this->proceedToNextStep
}
protected function filterTwo()
{
//perform some action and set
//$this->proceedToNextStep
}
protected function filterThree()
{
//do some filter and set
//$this->proceedToNextStep
}
}
I think the above class is enough to describe the problem . Is there any better approach/design pattern to accomplish this task ,probably using single class ?
Edit Got another approach , your comments please! (not tested)
class PipeAndFilter
{
protected $callStack
protected $input;
/** fail states -ve numbers , success stats +ve numbers */
protected $proceedToNextStep;
public function __construct(Array $input)
{
$this->input=$input;
$this->callStack=array();
$this->callStack[]=array($this,'filterOne'));
$this->callStack[]=array($this,'filterTwo'));
$this->callStack[]=array($this,'filterThree'));
}
public function process()
{
foreach($this->callStack as $filterStep){
call_user_func($filterStep);
if(!$this->isProceedNext()) break;
}
}
protected function isProceedNext()
{
return $this->proceedToNextStep > 0
}
protected function filterOne()
{
//perform some action and set $this->proceedToNextStep
}
protected function filterTwo()
{
//perform some action and set $this->proceedToNextStep
}
protected function filterThree()
{
//perform some action and set $this->proceedToNextStep
}
}