Skip to content

Instantly share code, notes, and snippets.

@Nav-Appaiya
Forked from letitride/command.sample.php
Created October 5, 2015 21:43
Show Gist options
  • Save Nav-Appaiya/7d149a23c050f17ff53b to your computer and use it in GitHub Desktop.
Save Nav-Appaiya/7d149a23c050f17ff53b to your computer and use it in GitHub Desktop.
php command
<?php
class Data
{
private $_value;
private $_error;
function __construct( $name, $value ){
$this->_name = $name;
$this->_value = $value;
}
public function validate_require(){
if( strlen( $this->_value ) == 0 ){
$this->_error = "require error";
return false;
}
return true;
}
public function validate_maxlength( $max_length ){
if( strlen( $this->_value ) > $max_length ){
$this->_error = "length $max_length over";
return false;
}
return true;
}
public function print_error(){
print $this->_error."\n";
}
}
abstract class Command
{
abstract function execute();
}
class ValidateRequireCommand extends Command
{
private $_data;
function __construct( $data ){
$this->_data = $data;
}
public function execute(){
if( ! $this->_data->validate_require() ){
$this->_data->print_error();
return false;
}
return true;
}
}
class ValidateMaxLengthCommand extends Command
{
private $_data;
private $_max_len;
function __construct( $data, $max_len ){
$this->_data = $data;
$this->_max_len = $max_len;
}
public function execute(){
if(! $this->_data->validate_maxlength( $this->_max_len ) ){
$this->_data->print_error();
return false;
}
return true;
}
}
class Invoker
{
private $commands = array();
public function add( $command ){
$this->_commands[] = $command;
}
public function clear(){
$this->_commands = array();
}
function invoke(){
foreach( $this->_commands as $command ){
if( ! $command->execute() ){
break;
}
}
}
}
//this instance is not abstract type
$reciever = new Data( "hoge", "" );
$invoker = new Invoker();
$invoker->add( new ValidateRequireCommand( $reciever ) );
$invoker->add( new ValidateMaxLengthCommand( $reciever, 5 ) );
$invoker->invoke();
$invoker->clear();
$reciever = new Data( "hoge", "abcdefg" );
$invoker->add( new ValidateRequireCommand( $reciever ) );
$invoker->add( new ValidateMaxLengthCommand( $reciever, 5 ) );
$invoker->invoke();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment