Created
December 11, 2012 00:42
-
-
Save letitride/4254716 to your computer and use it in GitHub Desktop.
php command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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