在执行方法的完整流程期间进行数据验证


data validation during full flow of executed methods

这个问题没有编程语言范围。

假设我们的控制器操作或任何服务使用的函数/方法很少。

class Controller {
    function ourAction () {
        $document = $this->getDocumentFromDB();
        if (!$document) {
            throw new NotFoundException;
        }
        $this->mailer->send($document);
    }
}
class Mailer {
    function send ($document) {
        if (!$document) {
         throw 'Exception('Document parameter is empty');
        }
    }
}

是否需要检查 mailer->send() 中的文档是否存在,或者由于控制器操作验证而没有必要?

我会改用类型提示:

class Mailer {
    function send (MailableDocument $document) {
    }
}
interface MailableDocument {
    //whatever document methods you use in the mailer
}

PHP会为你做肮脏的工作。

编辑:

无需在控制器中检查它:

class Controller {
    function ourAction () {
        try {
            $this->mailer->send($this->getDocumentFromDB());
        } catch ('UnexpectedValueException $e) {
            throw new NotFoundException(null, null, $e); //whatever parameters it requires.
        }
    }
}
class Mailer {
    function send ($document) {
        if (!$document) {
         throw 'UnexpectedValueException('Document parameter is empty');
        }
    }
}