php - 后备过度杀伤力?

标签 php optimization error-handling fallback

我没有编码方面的正式知识,希望有人能告诉我我是否对代码保持谨慎吗?

// Insert info to the db
if ($stmt = $db_connect->prepare("INSERT INTO db (col1, col2) VALUES (?, ?)")) {
    if(!$stmt->execute([$val1, $val2])) {
        exit("1:Faild to create deal");
    }
    // Get last id
    $id = (int)$db_connect->lastInsertId();
    $stmt->closeCursor();
} else { exit("0:Faild to create deal"); }

// Create the folder
if(!mkdir("folder/folder".$id)) {
    if($stmt = $db_connect->prepare("DELETE FROM db WHERE id=?")) {
        if(!$stmt->execute([$id])) {
            exit("1:Faild to create the directory -> Faild to remove the row from the database");
        }
        exit("Faild to create the directory");
    }
    exit("0:Faild to create the directory -> Faild to remove the row from the database");
}

我用相同的布局重复执行create folder语句两次。只是可重复的代码看起来有些过头了。

注意:我与主机一起使用的软件包只有MyISAM表,因此不能使用回滚。

如果失败了,我想撤消所有过去的事情。

有人可以给我一些最佳做法的指导,还是我做对了?

最佳答案

我重新构造并扩展了代码,并通过使用异常添加了一些简单的错误处理。
首先,您应该将PDO错误处理设置为异常模式:

$db_connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

然后,我将您的操作封装到函数中,可以将其放入一个单独的文件并将其包含在内,甚至将它们嵌套到类中:
/*** FUNCTIONS ***/
// insert info to the db
function dbInsertInfo($db_connect, $val1, $val2)
{
    $stmt = $db_connect->prepare("INSERT INTO db (col1, col2) VALUES (?, ?)");
    $stmt->execute([$val1, $val2]));
}
//-------------------------------

// get the last insert id
function dbGetId($db_connect)
{
    $id = (int)$db_connect->lastInsertId();
    $stmt->closeCursor();
    return $id;
}
//-------------------------------

// delete db-entry
function dbDeleteId($db_connect, $id)
{
    $stmt = $db_connect->prepare("DELETE FROM db WHERE id=?");
    $stmt->execute([$id]);
}
//-------------------------------

// create the folder
function createFolder($id)
{
    if(!mkdir("folder/folder".$id)) throw new Exception("Failed to create the directory");
}
//-------------------------------

然后这是您的所有try{ } catch{ }部分的过程,用于通过异常进行错误处理:
/* PROCEDURE */

// 01 | try to insert into db
try 
{
    dbInsertInfo($db_connect, $val1, $val2);
}
catch(PDOException $e)
{
    //if exception thrown, do not continue the script:
    echo "Unable to insert into DB: ".$e->getMessage();
    exit();
}
//-------------------------------

// 02 | try to get last insert id
$id = false;
try 
{
    $id = dbGetId($db_connect);
}
catch(PDOException $e)
{
    //if exception thrown, do not continue the script:
    echo "Unable to get last insert id from DB: ".$e->getMessage();
    exit();
}
//-------------------------------

// 03 | try to create folder // if it fails -> try to delete db entry
try 
{
    createFolder($id);
}
catch(Exception $e)
{
    // if exception caught, try to remove the corresponding DB entry:
    echo $e->getMessage();
    echo "<br />";
    echo "trying to remove DB entry now";

    // try to delete db entry
    try
    {
        dbDeleteId($db_connect, $id);
    }
    catch(PDOException $e)
    {
        //if exception thrown, do not continue the script:
        echo "Unable to delete from DB: ".$e->getMessage();
        exit();
    }
}
//-------------------------------
/* Everything worked fine if you get to this point of the code*/

对于您来说,这似乎只是一种技术上的过大杀伤力,但我认为,一旦您熟悉它,它的结构性就会更好,阅读起来会更好。此外,它仅分为3个步骤。

关于php - 后备过度杀伤力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25712694/

相关文章:

c++ - 有没有办法优化这个功能?

python - 打开文件时lxml中的密码错误

php - fatal error : Call to a member function prepare() on a non-object in

java - 您将如何优化(无代码重复)具有许多此类功能的 Java 代码

php - 调用JS函数时销毁 session 变量

sql - 优化两个日期之间的 BigQuery 聚合数据

php - 如何将 PHP 通知和警告发送到 error_log 而不是在网页上?

java - 找不到类 'org.apache.http.entity.mime.content.Filebody',从方法中引用

php - Laravel 5.1 创建用户不会插入添加的列?

php - 更新查询在 PHP 和 Mysql 中不起作用