我正在开发一个项目,其中 HTML 设计者使用 PHP 方法来检索内容。现在,是时候处理异常了,但我们在同时保持 HTML 漂亮、干净和语义以及 PHP 正确的同时遇到了问题。
在出现异常(exception)情况之前,HTML 模板具有以下内容:
<h2 class="title"><?php Content::getTitle() ?></h2>
现在,如果我们想处理异常,我们应该这样写:
<h2 class="title">
<?php
try {
Content::getTitle();
} catch (Exception $e) {
echo $e->getMessage();
}
?>
</h2>
一点也不干净。
或者
<?php
try {
// THE WHOLE TEMPLATE RENDERING!!!
} catch (Exception $e) {
echo $e->getMessage();
}
?>
这是 Not Acceptable ,因为它会在出现任何异常时停止渲染,而此时它应该报告问题并继续。
因此,我们正在考虑将 try/catch 内容放入方法本身中:
class Content {
public static function getTitle {
try {
if (something==happened) throw new Exception 'OMG!';
else {
DoTheJob();
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
目前看来可行,所以问题是:这是一个好的做法吗?有更好、更干的替代品吗?
最佳答案
是的,这很好。它被称为Template View Pattern :
The best way to work with dynamic webpages [sic] is to compose the dynamic Web page as you do a static page but put in markers that can be resolved into calls to gather dynamic information. Since the static part of the page acts as a template for the particular response, I call this a Template View.
更多详情请参阅Fowler, Patterns of Enterprise Application Architecture.
关于php - 如何处理 PHP 异常并保持语义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12579707/