All pastes #476683 Raw Edit

berry__

public php v1 · immutable
·published 2007-05-08 08:37 UTC
rendered paste body
<?phpclass fwValidationChain{  public function __construct ()  {    $this -> rules = array ();    $this -> logger = new fwLogger ();  }  public function addRule ( ruleInterface $rule )  {    $this -> rules [] = $rule;  }  public function runChain ( fwDataSpace $dataspace )  {    $return = true;    foreach ( $this -> rules AS $rule )    {      $return = $rule -> isSatisfied ( $dataspace, $this -> logger ) && $return;    }    return $return;  }}interface ruleInterface{  public function isSatisfied ( fwDataSpace $datasource, fwLogger $logger );}class NotEmptyRule implements ruleInterface{  private $fieldnames;  private $errormessage;  public function __construct ( $errormessage, $fieldname )  {    $parameters = func_get_args();    $this -> errormessage = array_shift( $parameters );    $this -> fieldnames = $parameters;  }  public function isSatisfied ( fwDataSpace $dataspace, fwLogger $logger )  {    $return = true;    foreach ( $this -> fieldnames AS $fieldname )    {      if ( $dataspace -> get ( $fieldname ) === false OR strlen ( $dataspace -> get ( $fieldname ) ) <= 0 )      {        $logger -> addMessage ( $fieldname, $this -> errormessage );        $return = false;      }    }    return $return;  }}class fwDataSpace{  public function __construct ( &$values = false )  {    if ( $values !== false )    {      $this -> values = $values;    }  }  public function set ( $key, $value )  {    $this -> values [ $key ] = $value;  }  public function get ( $key )  {    return ( isset ( $this -> values [$key]  ) ) ? $this -> values [$key] : false;  }}class fwLogger{  private $messages;  public function __construct ()  {    $this -> messages = array ();  }  public function addMessage ( $fieldname, $message )  {    $this -> messages [$fieldname] [] = sprintf ( $message, $fieldname );  }  public function getMessages ()  {    return $this -> messages;  }}/*** Model class User.**/class User{  public function __construct ()  {    $this -> validationChain = new fwValidationChain ();    $this -> validationChain -> addRule ( new NotEmptyRule ( '%s mag niet leeg zijn.', 'foo', 'bar' ) );  }  public function save ()  {    /*  Ik heb nog geen dataspace (die komt uit een fwRequest, maar dat heb ik even weggelaten),    zo'n dataspace kan POST, GET, SESSION, COOKIE, ENV of gewoon userdefined zijn */    $post = array ( 'foo' => 'Test', 'bar' => 'kip' );    $dataspace = new fwDataSpace ( $post );    if ( $this -> validationChain -> runChain ( $dataspace ) === false )    {      return false;    }    else    {      /* Hier zou bijvoorbeeld een save() van een ORM of ActiveRecordBase aangeroepen kunnen worden. */      return true;    }  }}$user = new User ();if ( $user -> save () === true ){  echo '\o/';}else{  echo ':(';}?>