【发布时间】:2011-12-28 03:30:03
【问题描述】:
我在继承和标准 PHP 库 (SPL) 提供的 hierarchy of Exceptions 方面遇到了一个棘手的问题。
我目前正在 PHP 中为基于 REST 的 API 构建一个帮助程序库。这些 API 可以以 JSON 对象的形式返回它们自己的错误消息,并且这些对象包含 PHP 异常提供的属性之外的信息。这是一个简单的例子:
{"error":{"time":"2011-11-11T16:11:56.230-05:00","message":"error message","internalCode":10}}
有时,“消息”包含可能受益于额外解析的内部结构。我喜欢抛出一个特定的异常子类的想法,就像这样:
$error = $json->error;
throw new UnexpectedValueException($error->message, $error-internalCode);
以后可以选择性地捕获:
catch (UnexpectedValueException $e)
{
...
}
现在我们遇到了一个难题:我想扩展 SPL 异常对象,以便它们可以具有“时间”属性,并执行额外的“消息”解析。但是,我想在它们的级别 扩展它们,而不是创建基 Exception 类的扩展,以便保留选择性捕获异常的能力。最后,如果可能的话,我想避免创建 13 个不同的子类(异常类型的数量defined in the SPL)。
理想情况下,我可以从父 customException 对象开始:
class customException
{
public $time;
public $message;
public $internalCode;
public function __construct($time, $message, $internalCode)
{
$this->time = $time;
$this->message = $message;
$this->internalCode = $internalCode;
}
public function parseMessage()
{
// Do some parsing of message
return $parsedMessage;
}
}
然后,我将有一个可以像这样调用的工厂类:
class ExceptionFactory
{
static public function createException(Exception $e, $exceptionParent)
{
$json = json_decode($e->message);
return new customException($json->time, $json->message, $json->internalCode) extends $exceptionParent; // Won't work, but hopefully you get the idea
}
}
阅读php dynamic class inheritance 后,我可能可以使用eval() 到达那里,但这对我来说感觉不对。如果我必须编写 13 个子类,那么我会发现自己想要对所需的父类 $exceptionParent 和 customException 使用多重继承。你会建议我如何解决这个困境?提前感谢您的想法!
【问题讨论】:
标签: php exception inheritance dynamic