Cakephp 使用Guzzle时如何将数据传递到侦听器?
我将Guzzle 3.8.1与CakePHP2.5.6结合使用,并调用Box API。我希望能够在访问令牌过期时刷新它。我遇到的问题是,我可能正在使用N个可能的访问令牌中的任意一个,并且我希望能够使用$account_id,该id在我定义它的函数的范围内。我不知道如何将它传递到侦听器定义的函数中,因为我自己并没有调用它。我确实看到$event变量中存在过期的access_令牌,但我必须找到它,然后从传递给Box的头解析它。我想我可以添加一个包含帐户id的自定义标题,但这似乎不是解决问题的好方法。我是否可以在请求中指定一个不会作为调用框的一部分添加的变量?非常感谢您的建议,谢谢 `Cakephp 使用Guzzle时如何将数据传递到侦听器?,cakephp,guzzle,boxapiv2,Cakephp,Guzzle,Boxapiv2,我将Guzzle 3.8.1与CakePHP2.5.6结合使用,并调用Box API。我希望能够在访问令牌过期时刷新它。我遇到的问题是,我可能正在使用N个可能的访问令牌中的任意一个,并且我希望能够使用$account_id,该id在我定义它的函数的范围内。我不知道如何将它传递到侦听器定义的函数中,因为我自己并没有调用它。我确实看到$event变量中存在过期的access_令牌,但我必须找到它,然后从传递给Box的头解析它。我想我可以添加一个包含帐户id的自定义标题,但这似乎不是解决问题的好方法。
`请将代码缩短到相关部分,或者至少显示sour代码失败的地方,好吗?到目前为止,我真的不明白你的问题在哪里,尽管我有一种感觉,它可能通过闭包来解决-请看:它实际上归结为这一行:$account=$Box->refresh\u token$account\id;$account\u id超出范围。在快速查看之后,似乎您认为闭包应该处理它是正确的。我会试着抽时间回去,试着从那时起我就做了一个变通,继续前进。谢谢
public function get_folder_list ($account_id = null, $parent_folder_id = null) {
// Get account
$this->Account = ClassRegistry::init('Account');
$account = $this->Account->findById($account_id);
$this->Account->log($account);
// If account doesn't exist, throw error
if(empty($account)) {
throw new NotFoundException(__('Account id not found: ' . $account_id));
}
// Call Box for folder list
$box_url = "https://api.box.com/2.0/folders/";
if (empty($parent_folder_id)) {
$box_url .= "0";
} else {
$box_url .= $parent_folder_id;
}
$this->Account->log($box_url);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$client = new Guzzle\Http\Client();
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$Account = new Account;
$Account->log($event);
$Box = new BoxLib;
$account = $Box->refresh_token($account_id);
$bearer = 'Bearer ' . $account['Account']['access_token'];
$request = $client->get($box_url, array('Authorization' => $bearer));
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
$request = $client->get($box_url, array('Authorization' => $bearer));
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
// HTTP codes 4xx and 5xx throw BadResponseException
$this->Account->log('Service exception!');
$this->Account->log('Uh oh! ' . $e->getMessage());
$this->Account->log('HTTP request URL: ' . $e->getRequest()->getUrl() . "\n");
$this->Account->log('HTTP request: ' . $e->getRequest() . "\n");
$this->Account->log('HTTP response status: ' . $e->getResponse()->getStatusCode() . "\n");
$this->Account->log('HTTP response: ' . $e->getResponse() . "\n");
}
$this->Account->log($response->json());
$json = $response->json();
$folder_list = array();
foreach ($json['item_collection']['entries'] as $folder) {
$folder_list[$folder['id']] = $folder['name'];
}
//$this->Account->log($folder_list);
return $folder_list;
}