【问题标题】:Appropriate use of die()?适当使用die()?
【发布时间】:2010-06-14 05:42:39
【问题描述】:

注意:我正在使用输出缓冲。它只是包裹在 head() 和 foot() 函数中。

我使用以下模板在我当前的 PHP 项目中创建页面:

<?php
include 'bootstrap.php';
head();
?>

<!-- Page content here -->

<?php
foot();
?>

以下示例是否适合使用 die()?另外,如果有的话,这会给我带来什么样的问题?

<?php
include 'bootstrap.php';
head();

try
{
    //Simulate throwing an exception from some class
    throw new Exception('Something went wrong!');
}
catch(Exception $e)
{
    ?>
    <p>Please fix the following error:</p>
    <p><?php echo $e->getMessage(); ?></p>
    <?php
    foot();
    die();
}

//If no exception is thrown above, continue script
doSomething();
doSomeOtherThing();

foot();
?>

基本上,我有一个包含多个任务的脚本,我正在尝试设置一种优雅的方式来通知用户输入错误,同时阻止脚本的其余部分执行。

谢谢!

【问题讨论】:

  • die('PHP')。我开玩笑,我开玩笑。

标签: php exception-handling error-handling die


【解决方案1】:

我会这样做:

head();
try {
    somethingPossiblyWithError();
    somethingElse();
} catch (Exception $e) {
    handleError();
}
foot();

不需要死亡。如果在somethingPossiblyWithError 中出现错误,则somethingElse 将被跳过。 foot 在这两种情况下都会被执行。

更新:我赞成 Shrapnel 上校的回答,因为我猜你没有考虑到这一点,这是一个宝贵的知识。在 PHP 中,您可以通过output buffering 获得等效功能,而无需显式传递值,但它并不那么漂亮 - 但是,如果您调用的函数将打印内容而不将它们作为值返回,那么它可以工作,所以有时它很有用知道。

【讨论】:

  • 感谢您的示例。我不认为这是可能的,但这显然是避免使用 die() 的好方法。
【解决方案2】:

整个页面结构错误。
虽然这是最普遍的新手错误。

在准备好所有数据之前,永远不要输出任何东西。
您的脚本可能会发送一些 HTTP 标头,可能会设置一些变量以在 header() 或任何内容中使用。

因此,模板的使用是必要的。
您必须将脚本分为两部分 - 获取数据部分和显示数据部分。
因此,您必须将 header() 函数移动得更低。
根据 Amadan 的回答,它可能是

<?php
include 'bootstrap.php';
try {
  getData();
} catch (Exception $e) {
    handleError();
}
head();
body();
foot();
?>

handleError() 函数可以设置适当的 HTTP 错误代码(404 或 500)并用错误消息文本替换正文模板。

【讨论】:

  • 输出缓冲就是为了这个。有时您想要的数据是您的脚本已经尝试发送的数据。但是,是的,更好地将数据处理与输出分开,这样您就不会在 php 代码中间有乱七八糟的 html(或您使用的任何模板系统)。
  • @Arkh 不,输出缓冲不会帮助您使用变量设置页面标题。
  • 嘿@Co​​l 感谢您的回复。不过,我不得不部分不同意。 “整个”页面结构没有错。我通过 bootstrap.php 包含(在脚本开头)获取大部分数据。我开始在 head() 内部进行输出缓冲,这对我来说似乎很有意义 b/c 之前没有输出的机会,并且它允许将变量传递给 head() 函数。输出缓冲在 foot() 函数内结束。现在,关于脚本的中间部分(head() 和 foot() 之间),我完全同意你的看法。我需要重构以允许在查看之前进行数据检索。谢谢!
  • 想知道你的想法
  • @letseatfood 在引导程序中收集的大多数数据都是无稽之谈,缓冲不会让您应用变量。只是获得更多的经验,你会看到。我不觉得解释显而易见的事情。
【解决方案3】:

不推荐您的方法有很多原因。你应该:

  • 分离表示和逻辑(看看 MVC 模式)
  • 避免程序化代码,编写面向对象的 PHP
  • 独立的用户和管理员体验(温和地处理错误)

示例,在上面实现:

<? $page->debug = true; ?>
<?= $page->getHead(); ?>
<?= $page->getBody(); ?>
<?= $page->getFoot(); ?>

class page {

   public debug;

   public function getBody() {
       try {
          //
       } catch (Exception $e) {
          $this->_errorhandler('message');
       }
   }

   protected function _errorhandler($message) {
        if ($this->debug) {
              // display error message
          } else {
             // display nothing, log the error
             // or throw concrete exception
             // or redirect
          }
   }
 ...
}

也不建议这样做(每个任务都需要许多单独的类),但您明白了重点:分离,而不是混合所有内容。

【讨论】:

  • 不建议短开放标签
猜你喜欢
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 2014-07-17
  • 2017-05-30
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
相关资源
最近更新 更多