database - 数据库插入调用应该返回什么?

标签 database model-view-controller

我有一个包含大量插入函数的数据源。每个函数都有一个应该插入数据库的项目列表。这些项目中的每一个都可以成功插入或不插入。如果没有成功插入,我想知道原因。

关于应从数据源插入函数返回的内容是否有最佳实践?

初步想法:

bool 型成功:不给我任何失败的理由

具有 bool 值成功和字符串原因的自定义响应对象:无法处理 >1 插入响应

自定义响应对象列表:似乎做我想做的......

最佳答案

如果是我,我会将我的 API 设置为在未正确插入行时抛出异常。

看起来像(仅供引用):

$dbo = new Database();

foreach ($items as $item) {

    try {
        $dbo->insert($item);

        Log::toLogfile('Row was successfully inserted');

    } catch (Exception $e) {

        // If an exception failed upon insert, I can log the message and move on
        error_log($e->getMessage());
    }
}

class Database
{
    public function insert(array $item) {

        // Here you can add any number of validators
        if (empty($item)) {
            throw new Exception(sprintf('Invalid $item array (%s)', serialize($item));
        }

        elseif (!array_key_exists('id', $item)) {
            throw new Exception(sprintf('Invalid $item[id] (%s)', serialize(item));
        }

        // Making a call to php function which returns bool
        //  No problem, we test for return value and throw exception accordingly
        if (!$this->dbo->insert($item)) {
            throw new Exception(sprintf('Row was not inserted (%s)', serialize($item));
        }

        // If we made it this far, we have successfully inserted a row
        //  And code resumes back up after call to this function was made
    }

抛出异常是将消息返回给调用代码的最佳方式,它会强制调用代码处理异常。通过将我们的 $dbo->insert($item) 调用包装在 try/catch block 中,我们可以捕获异常,记录它,然后移动到数组中的下一个项目。

关于database - 数据库插入调用应该返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8981339/

相关文章:

android - 拦截数据库错误 "file is encrypted or is not a database"

c# - Automapper 在第一次调用时正确映射,但在第二次调用时跳过属性

javascript - AngularJS - 链接后修改html元素

asp.net-mvc - MVC DDD : Is it OK to use repositories together with services in the controller?

c# - MVC 模式差异

mysql - 如何从同一张表中获取最小(日期)、最大(日期)及其数量?

php - 这是用于数据库实现的良好 PHP OOP 结构吗?

php - MVC : should view talk with model directly?

mysql - 如何将 form/golang 中的连接池连接到没有数据库的实例?

java - 将包含百万值的 csv 文件上传到 mysql 中的特定列