我已将Google Calendar API放在包装类中
Class cl_calendar
{
private $db;
private $google_client;
private $google_service;
private $calendar_id;
public function __construct($calendar_id = 'primary')
{ $this->db = new cl_database();
// ...
$this->do_initialise();
}
public function do_initialise()
{ require_once '../plugins/google-api-php-client-2.2.1/vendor/autoload.php';
$this->google_client = $this->getClient();
$this->google_service = new Google_Service_Calendar($this->google_client);
}
private function getClient()
{ $client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('../plugins/google-api-php-client-2.2.1/client_secret.json');
$client->setAccessType('offline');
$credentialsPath = $this->expandHomeDirectory('../plugins/google-api-php-client-2.2.1/credentials.json');
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim('...');
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
private function expandHomeDirectory($path)
{ $homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
public function do_cleanup_deleted_events() {
$qry = 'select ...';
$sql = $this->db->do_select($qry);
foreach ($sql as $row) {
$event = $this->google_service->events->get($this->calendar_id, $row['calendar_id']);
if ($event) {
if ($event['status'] == 'cancelled') { // DELETED
$qry = 'update ...';
$this->db->do_update($qry);
}
}
}
echo 'ok';
return true;
}
}
到目前为止,一切都很好。这段代码可以完美地工作(省去了一些不必要的Google API代码和密钥。
但是...当我删除“ echo'ok'”时,浏览器返回“此页面不起作用”; do_cleanup_deleted_events()方法中的一行。可能很明显,但我不明白为什么会这样。
我创建类并运行方法的代码:
require_once('../logic/calendar.class.php');
$calendar = new cl_calendar('primary');
$calendar->do_cleanup_deleted_events();
答案 0 :(得分:1)
找到了。好吧。
所以我要查找的事件不再存在于该日历中。因此,错误。当我将代码放在try catch中时,它可以解决问题。
但是,删除try catch并放入“ echo'ok'”;也可以“解决”问题。我发现奇怪的是,放置回声后错误不会持续存在。不知道为什么会这样。