@blog.justoneplanet.info

日々勉強

Chain of Responsibility

■コード

AbstractValidationHandler

abstract class AbstractValidationHandler {
    private $nextHandler;
    public function __construct() {
        $this->nextHandler = null;
    }
    public function setHandler(ValidationHandler $handler) {
        $this->nextHandler = $handler;
        return $this;
    }
    public function getNextHandler() {
        return $this->nextHandler;
    }
    public function validate($input) {
        $result = $this->execValidation($input);
        if(!$result) {
            return $this->getErrorMessage();
        }
        else if(!is_null($this->getNextHandler())) {
            return $this->getNextHandler()->validation($input);
        }
        else {
            return true;
        }
    }
    protected abstract function execValidation($input);
    protected abstract function getErrorMessage();
}

AlphaNumericValidation.php

class AlphaNumericValidation extends AbstractValidationHandler {
    protected function execValidation($input) {
        return preg_match('/^[0-9a-zA-Z]+$/', $input);
    }
    protected function getErrorMessage() {
        return '半角英数字で!';
    }
}

NumericValidation.php

class NumericValidation extends AbstractValidationHandler {
    protected function execValidation($input) {
        return preg_match('/^[0-9]+$/', $input);
    }
    protected function getErrorMessage() {
        return '半角数字で!';
    }
}

■クライアントコード

$alphaNumericValidation = new AlphaNumericValidation();
$handler = $alphaNumericValidation->setHandler(new NumericValidation());
$result = $hander->validete($input);
if($result) {
    // ok
}
else {
    // error
}

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment