1

这是我现在的代码:

$cloud = new Rackspace('https://identity.api.rackspacecloud.com/v2.0/', $php_cloudconfig['credentials']);
$array_creds = getCredentials();
$cloud->ImportCredentials($array_creds);

$array_creds = $cloud->ExportCredentials();
setCredentials($array_creds['authorization_token'], $array_creds['expiration'], $array_creds['tenant_id'], $array_creds['service_catalog']);

function getCredentials() {
    $sql_get_credential = "SELECT * FROM cloud_apiconnection";
    $q = $conn->prepare($sql_get_credential);
    return $q->execute();
}

function setCredentials($authorization_token, $expiration, $tenant_id, $service_catalog)     {
    $sql_insert = "INSERT INTO cloud_apiconnection (authorization_token, expiration, tenant_id, service_catalog) VALUES (:authorization_token, :expiration, :tenant_id, :service_catalog)";
    $q = $conn->prepare($sql_insert);
    $q->execute(array(':authorization_token' => $authorization_token, ':expiration' => $expiration, ':tenant_id' => $tenant_id, ':service_catalog' => $service_catalog));
}

有没有办法检测凭据是否在以下位置更新:$cloud->ImportCredentials($array_creds); ?

我在徘徊,因为如果我不需要的话,我不想写信给数据库。

这也是管理我与 RackSpace API 的连接的最佳策略吗?

4

1 回答 1

2

这似乎是维护持久会话的好策略,因为您正在重用现有的令牌 ID。唯一的其他建议是将您的凭据缓存在本地文件中,而不是进行 MySQL 事务。您实际上并不需要存储您的租户 ID 和服务目录,因为这些都可以通过软件层轻松检索。

要检查现有令牌的有效性,我会这样做:

$connection = new Rackspace(...);

// Import existing credentials
$credentials = getCredentials();
$connection->importCredentials($credentials);

// Authenticate against the API to make sure your token is still valid
$connection->authenticate();

// Compare result
$newCredentials = $connection->exportCredentials();

if ($newCredentials['authorization_token'] != $credentials['authorization_token']) {
   // You know it's been updated, so save new ones
   setCredentials();
}

authenticate()方法所做的只是对 Rackspace API 执行请求;根据结果​​,它有效地让您知道您现有的东西是否仍然有效。当其他方法调用时authenticate(),它们通常会事先进行另一项检查:检查到期值(即不是过去)。您可以实现他们所做的相同的事情(以确定是否需要刷新和保存凭据):

if (time() > ($credentials['expiration'] - RAXSDK_FUDGE)) {
   // They're old, you need to call authenticate()
} else {
   // They seem to be still valid. Sweet!
}

顺便说一句,我们最近更改了此功能,以便exportCredentials()调用authenticate()- 所以这意味着您不需要自己调用它。但是对于您当前的版本,值得保留它。

这能回答一切吗?

于 2013-09-06T07:31:31.007 回答