Chain of Responsibility

ヴァージョン5で。

  • だらだらと分岐を書くのはいいかげんやめようと。
<?php
ini_set('display_errors','On');

$str = 'MOGE';

$chk = new NotNull();
$chk->set(new NotHoge())->set(new NotMoge());
$rs = $chk->execute($str);

print "<pre>";
print_r($chk);
print_r($rs);

//----------------------------------
class InpChk{
	var $list;
	function InpChk(){
		$this->list = null;
	}
	function set($method){
		$this->list = $method;
		return $this->list;
	}
	function next(){
		return $this->list;
	}
	function execute($input){
		$result = $this->checkAction($input);
		if(!$result){
			return $this->errorAction();
		} else if(!is_null($this->next())){
			$next = $this->next();
			return $next->execute($input);
		} else {
			return TRUE;
		}
	}
	function checkAction(){
		/* 子クラスで実装 */	
	}
	function errorAction(){
		/* 子クラスで実装 */
	}
}

class NotNull extends InpChk{
	function checkAction($input){
		return ($input != '');
	}
	function errorAction(){
		return "ERROR_NULL";
	}
}
class NotHoge extends InpChk{
	function checkAction($input){
		return ($input != 'HOGE');
	}
	function errorAction(){
		return "ERROR_HOGE";
	}
}
class NotMoge extends InpChk{
	function checkAction($input){
		return ($input != 'MOGE');
	}
	function errorAction(){
		return "ERROR_MOGE";
	}
}
?>

ヴァージョン4系で

<?php
ini_set('display_errors','On');

$str = 'MOGE';

$chk = new NotNull();
$chk2 = $chk->set(new NotHoge());
$chk2->set(new NotMoge());
$rs = $chk2->execute($str);

print "<pre>";
print_r($chk);
print_r($rs);

//----------------------------------
class InpChk{
	var $list;
	function InpChk(){
		$this->list = null;
	}
	function set($method){
		$this->list = $method;
		return $this->list;
	}
	function next(){
		return $this->list;
	}
	function execute($input){
		$result = $this->checkAction($input);
		if(!$result){
			return $this->errorAction();
		} else if(!is_null($this->next())){
			$next = $this->next();
			return $next->execute($input);
		} else {
			return TRUE;
		}
	}
	function checkAction(){
		/* 子クラスで実装 */	
	}
	function errorAction(){
		/* 子クラスで実装 */
	}
}

class NotNull extends InpChk{
	function checkAction($input){
		return ($input != '');
	}
	function errorAction(){
		return "ERROR_NULL";
	}
}
class NotHoge extends InpChk{
	function checkAction($input){
		return ($input != 'HOGE');
	}
	function errorAction(){
		return "ERROR_HOGE";
	}
}
class NotMoge extends InpChk{
	function checkAction($input){
		return ($input != 'MOGE');
	}
	function errorAction(){
		return "ERROR_MOGE";
	}
}
?>