I'm playing with a simple (for now) project in PHP with Google Calendar API. I have posted the code here in order to improve my programming style about whatever you think it's worth suggesting. Thank you.

As you can see, at the moment the script listEvents.php retrieves all the events in the last 7 days from primary calendar, and deletes the events whose title is included in the array deletable.

Below is the code so far:



require_once (__DIR__."/beAuthorized.php");
require_once (__DIR__."/calConfig.php");

$beAuthorized = new beAuthorized();
$calConfig = calConfig::getInstance();

$deletable = $calConfig->getDeletable();
$calendarId = $calConfig->getCalendarId();

$optParams = array(
  'orderBy' => 'startTime',
  'singleEvents' => true,
  'timeMin' => date('Y-m-d\TH:i:sP', strtotime('-7 days')),
  'timeMax' => date('c'),

try {
    $service = $beAuthorized->getService();
    $results = $service->events->listEvents($calendarId, $optParams);
    $events = $results->getItems();
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";

if (!empty($events)) {
    foreach ($events as $event) {
        if (in_array($event->getSummary(), $deletable)) {
               $service->events->delete($calendarId, $event->getId());


require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');

class beAuthorized
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
    private function getClient()
        $client = new Google_Client();
        $client->setPrompt('select_account consent');

        // Load previously authorized token from a file, if it exists.
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        $tokenPath = 'token.json';
        if (file_exists($tokenPath)) {
            $accessToken = json_decode(file_get_contents($tokenPath), true);

        // If there is no previous token or it's expired.
        if ($client->isAccessTokenExpired()) {
            // Refresh the token if possible, else fetch a new one.
            if ($client->getRefreshToken()) {
            } else {
                // Request authorization from the user.
                $authUrl = $client->createAuthUrl();
                printf("Open the following link in your browser:\n%s\n", $authUrl);
                print 'Enter verification code: ';
                $authCode = trim(fgets(STDIN));

                // Exchange authorization code for an access token.
                $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

                // Check to see if there was an error.
                if (array_key_exists('error', $accessToken)) {
                    throw new Exception(join(', ', $accessToken));
            // Save the token to a file.
            if (!file_exists(dirname($tokenPath))) {
                mkdir(dirname($tokenPath), 0700, true);
            file_put_contents($tokenPath, json_encode($client->getAccessToken()));
        return $client;

    * Returns a service object.
    public function getService() 
        // Get the API client and construct the service object.
        $client = $this->getClient();
        $service = new Google_Service_Calendar($client);
        return $service;



require_once (__DIR__."/singleton.php");

class calConfig extends singleton
    private $calendarId;
    private $deletable;

    protected function __construct()
          if(!isset($this->calendarId)) {
               $this->calendarId = 'primary';

          if(!isset($this->deletable)) {
              $this->deletable = array('Test', 'bye', 'one');

     public function getCalendarId() {
         return $this->calendarId;

     public function getDeletable() {
          return $this->deletable;



class singleton
    private static $instances = [];
    protected function __construct() { }
    protected function __clone() { }

    public function __wakeup()
        throw new \Exception("Cannot unserialize singleton");

    public static function getInstance()
        $subclass = static::class;
        if (!isset(self::$instances[$subclass])) {
            self::$instances[$subclass] = new static;
        return self::$instances[$subclass];

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.