Been playing with some code and just thought I'd share for some feedback.
Basically involved using create a finite state machine and using a dependency injector for actions, atm it seems very neat.
And an simple looping example..PHP Code:
interface Action
{
function execute();
}
class Processor implements Action
{
protected $injector;
protected $transitions;
const START = 0; // starting state
function __construct(DependancyInjector $injector)
{
$this->injector = $injector;
$this->transitions = array();
}
/*
@param state - is a key, and either $state or $action is the class name for the action implementation
@param outgoingStates - is an optional array of state => return-value pairs. (Reversed due to PHP index limitations.)
*/
function addState($state, array $outgoingStates = null, $action = null)
{
$this->injector->registerComponent($state, is_null($action) ? $state : $action);
$this->transitions[$state] = $outgoingStates;
}
function execute()
{
$state = self::START;
do
{
$action = $this->injector->getInstance($state);
$r = $action->execute();
// translate the current state & return value into the new state.
$states = $this->transitions[$state];
$state = is_array($states) ? array_search($r, $states) : false;
}
while ($state !== false);
}
}
PHP Code:
class LoopState
{
public $text = '';
}
class SimpleLooping extends Processor
{
function __construct(DependancyInjector $injector)
{
parent::__construct($injector);
$this->addState(self::START, array('AppendOneChar' => false, 'MetMinimumLength' => true), 'MeetsMinimumLength');
$this->addState('AppendOneChar', array(self::START => true));
$this->addState('MetMinimumLength');
}
}
abstract class LoopAction implements Action
{
protected $state;
function __construct(LoopState $state) { $this->state = $state; }
}
class MeetsMinimumLength extends LoopAction
{
function execute() { return strlen($this->state->text) >= 5; }
}
class AppendOneChar extends LoopAction
{
function execute() { $this->state->text .= chr(mt_rand(ord('a'), ord('z'))); return true; }
}
class MetMinimumLength extends LoopAction
{
function execute() { echo $this->state->text; }
}
$di = new DependancyInjector();
$di->registerCachedComponent('LoopState');
$dii = new DependancyInjector($di);
$loop = new SimpleLooping($dii);
$loop->execute();





and i'm sure it would work
Bookmarks