我正在製作一個PHP API,並且正在調用一個函數來從我們的DBHandler中提取請求。當我收到'/ attendees'函數時,我正確地提取數據。但是我想在api的每個調用中添加身份驗證。我們通過一個參數傳入DBHandler來指定使用哪個連接字符串(因爲我們有多個)。如果字符串被定義爲空,它將使用標準的連接字符串。PHP在調用兩次時無法在函數中重新聲明對象
'認證'功能需要使用標準連接字符串,而'/ attendees'則需要不同的連接字符串。正如所提到的'/參加者'本身很好地工作,但是當我嘗試執行sql時添加驗證錯誤。我知道這是因爲身份驗證正在使用不同的連接字符串,並以某種方式覆蓋連接。
require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';
ini_set('display_errors', 1);
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$user_id = NULL;
function authenticate(\Slim\Route $route) {
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$dm_config = null;
if (isset($headers['Auth'])) {
$db = new DbHandler($dm_config);
$api_key = $headers['Auth'];
if (!$db->isValidApiKey($api_key)) {
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoRespnse(401, $response);
$app->stop();
} else {
$response["error"] = false;
$response["message"] = "Auth Accepted";
}
} else {
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
}
$app->get('/attendees','authenticate', function() {
global $event_id;
$headers = apache_request_headers();
$event_id = $headers['Eventid'];
$dm_config = $headers['Dm'];
$user_id = null;
$response = array();
$db = new DbHandler($dm_config);
$result = $db->getAttendees($user_id, $event_id);
$response["error"] = false;
$response["nav"] = array();
while ($task = $result->fetch_assoc()) {
$tmp = array();
$tmp["ea.id"] = $task["ea.id"];
array_push($response["nav"], $tmp);
}
echoRespnse(200, $response);
});
我該如何獲得調用同一個對象但分開使用的函數?
一個新手的錯誤,但遺憾的是沒有任何區別 – gsusonline
在'身份驗證在這兩個功能由全球關鍵字訪問它( )'變量'$ dm_config'作爲null傳遞給構造函數。這是故意的嗎? – iliaz
是的,構造函數知道它是否提供null來使用特定的連接字符串 – gsusonline