dpsu84620 2011-08-02 12:47
浏览 19
已采纳

如何使用MVC架构在PHP中抛出错误

I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure how to handle errors. For example:

class AM_Products extends AM_Object 
{
    public function save( $new_data = array() ) 
    {
        // Validate input

        // Save input
    }
}

If I pass invalid input to save, should I throw an exception like this:

class AM_Products extends AM_Object 
{
    public function save( $new_data = array() ) 
    {
        // Validate input
        if ( ! validate( 'text', $new_data['name'] ) ) {
            throw new Exception( 'Invalid data entered' );
        }

        // Save input
    }
}

Or instead, should I add an extra function and leave it to the view/controller:

if ( $product->save( $data )->has_error() ) {
    $error = $product->get_error();
}

echo '<p>' . $error . '</p>';
  • 写回答

2条回答 默认 最新

  • dongzhuang6177 2011-08-02 12:58
    关注

    Don't throw an exception. Exceptions are for exceptional situations - invalid data entered into a form should not trigger an exception.

    Your model should have some sort of error state set, either on the model itself or on the individual fields. The post-back should "fall through" and display the same form that was originally shown, with error messages and/or highlighted fields indicating where the error is so the user can fix it.

    Throwing exceptions for validation is going to lead to a very fragile and difficult to use system. What happens if you want to simply show the user that one of the fields they supplied is invalid and give them a chance to correct it? How are you going to catch an exception and know how to display the associated record/form?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?