Ser*_*ize 4 php validation error-handling return-value
我有一个使用方法链接的验证类.我希望能够TRUE/FALSE像这样进行单一检查:
if ($obj->checkSomething()) {}
Run Code Online (Sandbox Code Playgroud)
但也像这样的链方法:
if ($obj->checkSomething()->checkSomethingElse()) {}
Run Code Online (Sandbox Code Playgroud)
但问题是,如果一个方法返回FALSE,它将不会发送回一个对象,从而打破以此错误结束的方法链:
Fatal error: Call to a member function checkSomething() on a non-object in ...
Run Code Online (Sandbox Code Playgroud)
我是否必须选择单个方法返回调用或方法链接,还是有解决方法?
一个想法是设置一个内部标志来指示成功或失败,并通过另一种方法访问它,同时在每个方法中检查该标志,如果设置则不做任何事情.例如:
class A {
private $valid = true;
public function check1() {
if (!$this->valid) {
return $this;
}
if (!/* do actual checking here */) {
$this->valid = false;
}
return $this;
}
public function check2() {
if (!$this->valid) {
return $this;
}
if (!/* do actual checking here */) {
$this->valid = false;
}
return $this;
}
public function isValid() {
return $this->valid;
}
}
// usage:
$a = new A();
if (!$a->check1()->check2()->isValid()) {
echo "error";
}
Run Code Online (Sandbox Code Playgroud)
为了最小化每个函数中的样板检查,您还可以使用魔术方法__call().例如:
class A {
private $valid;
public function __call($name, $args) {
if ($this->valid) {
$this->valid = call_user_func_array("do" . $name, $args);
}
return $this;
}
private function docheck1() {
return /* do actual checking here, return true or false */;
}
private function docheck2() {
return /* do actual checking here, return true or false */;
}
public isValid() {
return $this->valid;
}
}
Run Code Online (Sandbox Code Playgroud)
用法与上述相同:
$a = new A();
if (!$a->check1()->check2()->isValid()) {
echo "error";
}
Run Code Online (Sandbox Code Playgroud)