重构PHP函数代码以提高可读性

时间:2018-07-09 12:06:21

标签: php

我有这个Class函数,它具有更新会话ID:

/**
 * update session id in database
 *
 * @access public
 * @static static method
 * @param  string $userId
 * @param  string $sessionId
 */
public static function updateSessionId($userId, $sessionId = null)
{
    $database = DatabaseFactory::getFactory()->getConnection();
    $sql = "UPDATE users SET session_id = :session_id WHERE user_id = :user_id";

    $query = $database->prepare($sql);
    $query->execute(array(':session_id' => $sessionId, ":user_id" => $userId));
}

现在,我需要使用名称客户更新另一个数据库表。我有两个选择:

向此函数添加新的自变量check,如下所示:

public static function updateSessionId($userId,$check, $sessionId = null)

    if($check == 'users'){
     $sql = "UPDATE users SET session_id = :session_id WHERE user_id = :user_id";

..................

    } else {

     $sql = "UPDATE customers SET session_id = :session_id WHERE customer_id = :user_id";
........................
        }

或者为这样的客户创建/添加新功能:

public static function updateCustomerSessionId($userId, $sessionId = null)
{.......}

性能代码的最佳方法是什么?!

1 个答案:

答案 0 :(得分:0)

这就是我要做的

protected static $allowedTables = array('users', 'customers');

public static function updateSessionId($table, $userId, $sessionId = null)
{
    if (in_array($table, MySessionHandler::$allowedTables)) {

        $database = DatabaseFactory::getFactory()->getConnection();
        $sql = "UPDATE {$table} SET session_id = :session_id WHERE user_id = :user_id";

        $query = $database->prepare($sql);
        $query->execute(array(':session_id' => $sessionId, ":user_id" => $userId));
    }
}

我在这里看到的主要好处是,您可以轻松添加或删除表名。