假设我们有一些通过组合构建的对象层次结构。是否有任何模式可以在内部对象中注册业务逻辑错误并将它们传递给上层对象?
我只是厌倦了所有这些addErrors,每个级别的getErrors,我觉得我做错了什么。
我知道异常,但我不介意在这种情况下如何使用它们。业务逻辑错误在技术上不是危急情况,应该会导致程序执行中断。实际上根本不应该中断,因为我们需要记录错误并继续前进。
提前感谢您分享您的智慧和知识)
小片段来说明问题:
class ErrorContainer {
private $errors = array();
function addError($error) { if (!is_array($error)) { $this->errors[] = $error;} else { $this->errors = array_merge($this->errors, $error); } }
function getErrors() { return $this->errors[]; }
function hasErrors() { return !empty($this->errors); }
}
class Processor extends ErrorContainer {
function process($account_id, $orders) {
$account = new Account();
if (!$account->loadById($account_id)) { $this->addErrors($account->getErrors);}
foreach ($orders as $order_id) {
$order = new Order();
if (!$order->loadById($order_id)) { $this->addErrors($order->getErrors);}
}
}
return $this->hasErrors();
}
class Account extends ErrorContainer {
function loadById($account_id) {
$account = select_from_database($account_id);
if (!$account) { $this->addError("Account is missing"); }
if (!$account['active']) { $this->addError("Account is inactive"); }
// and so on, some checks may add errors in a cycle
return $this->hasErrors();
}
}
class Order extends ErrorContainer {} // very similar to Account, but has its own checks
//Usage:
$errors = array();
$items = load_items_from_xml($xml);
foreach ($items as $item) {
$processor = new Processor();
if (!$processor->process($item['account_id'], $item['orders'])) {
$errors = array_merge($errors, $processor->getErrors());
}
}