Php 在执行方法的整个流程中进行数据验证
这个问题是没有编程语言的范围 假设控制器操作或任何服务使用的函数/方法很少Php 在执行方法的整个流程中进行数据验证,php,Php,这个问题是没有编程语言的范围 假设控制器操作或任何服务使用的函数/方法很少 class Controller { function ourAction () { $document = $this->getDocumentFromDB(); if (!$document) { throw new NotFoundException; } $this->mailer->send($
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');
}
}
}
我建议根据标记的语言添加代码片段,以避免困惑用户的进一步否决。理论上,Mailer不应该知道您的控制器是否存在,或者它是做什么的。Mailer应该自己进行验证。这样,你可以在任何地方使用Mailer。有些情况下,这是不可能的。如果$document是数组,可能需要验证它的emptynessure。它也不适用于程序php4。正如Magnus所说,Mailer应该是独立的,并检查正常运行所需的所有数据是否都已通过。没有任何假设,它是在哪个上下文中被调用的,以前做过什么检查。请参阅更新的答案。