我有一个包含大量插入函数的数据源。每个函数都有一个应该插入数据库的项目列表。这些项目中的每一个都可以成功插入或不插入。如果没有成功插入,我想知道原因。
关于应从数据源插入函数返回的内容是否有最佳实践?
初步想法:
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/