3 回答

TA貢獻1810條經驗 獲得超4個贊
創建一個包含您要執行的所有驗證的數組。數組的每個元素都必須是可調用的。迭代并盡早退出。如果所有驗證器都通過了,那就好了。
private function hasValidContent(string $content) : bool
{
? ? $validators = [
? ? ? ? // instance method
? ? ? ? [$this, 'hasMoreThanOneChar'],
? ? ? ? // callable class
? ? ? ? new class {
? ? ? ? ? ? public function __invoke(string $content)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return ...;
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? // anonymous function
? ? ? ? function (string $content): bool {
? ? ? ? ? ? return ...;
? ? ? ? }
? ? ];
? ? foreach ($validators as $validate) {
? ? ? ? if (!$validate($content)) {
? ? ? ? ? ? return false;
? ? ? ? }
? ? }
? ? return true;
}

TA貢獻1876條經驗 獲得超7個贊
我推斷您正在尋找責任鏈模式。
例如,假設您有三個類:鎖、警報和燈,用于檢查房屋的狀態。
abstract class HomeChecker {
protected $successor;
public abstract function check(Home $home);
public function succeedWith($successor) {
$this->successor = $successor;
}
public function next(Home $home) {
$this->successor->check($home);
}
}
class HomeStatus {
public $locked = true;
public $alarmOn = true;
public $lightsOff = true;
}
class Locks extends HomeChecker {
public function check(Home $home) {
if(!$home->locked) {
throw new Exception('The doors are not locked'); // or basically whatever you want to do
}
$this->next($home);
}
}
class Alarm extends HomeChecker {
public function check(Home $home) {
if(!$home->alarmOn) {
throw new Exception('The Alarms are not on'); // or basically whatever you want to do
}
$this->next($home);
}
}
class Lights extends HomeChecker {
public function check(Home $home) {
if(!$home->lightsOff) {
throw new Exception('The lights are still on!'); // or basically whatever you want to do
}
$this->next($home);
}
}
$locks = new Locks();
$alarm = new Alarm();
$lights = new Lights();
$locks->succeedWith(new Alarm); // set the order in which you want the chain to work
$alarms->succeedWith(new Lights);
$locks->check(new HomeStatus);
所有三個類:Locks、Lights 和 Alarm 都擴展了一個名為HomeChecker的類,該類基本上具有一個抽象檢查方法以確保子類確實實現該方法以及兩個名為successWith和next 的方法。successWith 方法用于設置一個后繼者,如果當前執行的方法返回 true(意味著沒有錯誤),則將調用該后繼者。下一個方法本質上調用了鏈接起來的下一個方法。
通過這一行,我們開始了這個鏈,如果locks類的check 方法$locks->check(new HomeStatus);中的檢查失敗,則會拋出一個錯誤,并且執行將停止,否則它將調用HomeChecker 類的下一個方法,該方法最終將調用 check 方法我們安排的下一堂課
$locks->succeedWith(new Alarm); // set the order in which you want the chain to work
$alarms->succeedWith(new Lights);
在這些行中。
所以通過這種方式我們可以非常優雅地進行鏈式檢查。我希望這能幫到您。

TA貢獻1815條經驗 獲得超10個贊
一個建議是讓驗證方法拋出 anException而不是返回trueand false(成功時不返回任何內容)。
例如:
Class Validator {
public static function assertString($string) {
if (!is_string($string)) {
throw new Exception('Type mismatch.');
}
}
public static function assertStringLength($string, $min, $max) {
if (strlen($string) < $min || strlen($string) > $max) {
throw new Exception('String outside of length boundaries.');
}
}
}
你的代碼看起來像這樣:
try {
Validator::assertString($string);
Validator::assertStringLength($string, 4, 50);
} catch (Exception $e) {
// handle invalid input
}
請注意,我的函數是靜態的,在這種情況下有意義,但不一定總是如此。
- 3 回答
- 0 關注
- 169 瀏覽
添加回答
舉報