Symfony 2 and Google Calendar integration

    When creating a modern web project, you can not do without working with external services. Recently, we had the task of working with calendars. In this article I would like to talk about some aspects of integrating a project on Symfony2 with Google Calendar.

    Key receipt


    To exchange data with google you need to get the key. Our site will seek information invisibly to the user, so we need a key for the service account. To get the key you need to go to the console for developers . Add an application, go to the Api tab and activate the calendar. Now you can get the key in the Credentials tab.
    There is a json or p12 option. There is not much difference, it depends on what is more convenient for you.

    Google Api Module


    There is an api client for working with google services . Install it through composer
    php composer.phar require google / apiclient

    Make a small wrapper and declare it as a service.
    class Google
    {
        /* @var \Google_Client */
        private $client;
        /* @var \Google_Service_Calendar */
        private $calendar;
        private $scope;
        public function __construct($scope)
        {
            $this->client = new \Google_Client();
            $this->scope = $scope;
        }
        public function setCredentialsP12($p12Path, $email)
        {
            $credentials = new \Google_Auth_AssertionCredentials(
                $email,
                $this->scope,
                file_get_contents($p12Path)
            );
            $this->client->setAssertionCredentials($credentials);
        }
        public function setCredentialsJson($jsonPath)
        {
            $this->client->loadServiceAccountJson($jsonPath, $this->scope);
        }
        /**
         * @return \Google_Service_Calendar
         */
        public function getCalendar()
        {
            if (!$this->calendar) {
                $this->calendar = new \Google_Service_Calendar($this->client);
            }
            return $this->calendar;
        }
    }
    


    services:
        google.client:
            class: MyBundle\Google
            arguments: ['https://www.googleapis.com/auth/calendar.readonly'] # Сейчас нам нужны только права на чтение календаря
    

    The methods setCredentialsP12 and setCredentialsJson are needed in order to transfer keys inside our service. The getCalendar method returns the prepared calendar object and we do not need to supplement it somehow outside our service.

    Key connection


    We can have different keys in different environments, and each developer can have his own key. Therefore, we will transmit the key to the service depending on the availability of certain parameters that can be set in the local config. To do this, write and connect CompilerPass.
    use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    class CredentialsPass implements CompilerPassInterface
    {
        public function process(ContainerBuilder $container)
        {
            $googleClient = $container->getDefinition('google.client'); //Имя сервиса который мы объявили в предыдущем абзаце
            if ($container->hasParameter('google_p12_path') && $container->hasParameter('google_p12_email')) {
                $path = $container->getParameter('google_p12_path');
                $email = $container->getParameter('google_p12_email');
                $googleClient->addMethodCall('setCredentialsP12', [$path, $email]);
            } elseif ($container->hasParameter('google_json_path')) {
                $googleClient->addMethodCall('setCredentialsJson', [$container->getParameter('google_json_path')]);
            }
        }
    }
    

    And now we just need to write in the local config.
    parameters:
        google_p12_path: my-certificate.p12
        google_p12_email: my-email@mail.com
    
    or
    parameters:
        google_json_path: my-certificate.json
    


    Getting a list of events


    Now we have a service and we can request a list of events.
    try {
        /* @var $start \DateTime */
        $start;
        /* @var $end \DateTime */
        $end;
        $events = $google->getCalendar()->events->listEvents('example@mail.com', [
            'timeMin' => $start->format('c'),
            'timeMax' => $end->format('c'),
        ]);
    } catch (\Google_Service_Exception $exception) {
        //TODO implement error catching
    }
    

    Each calendar has its own unique email (example@mail.com in the example above). Using the listEvents method here, we get all the events from our calendar for a certain period of time. Google uses the ISO 8601 standard for time parameters (timeMin, timeMax), so just use the letter c to format the time.

    Instead of a conclusion


    After spending a little time, we gain access from our project to google calendar. Further you can develop this integration, for example, you can organize a more complex search or add events from our project. And if you are ready to entrust your calendars (or maybe not yours) to Google, then you can get a very powerful tool for cheap, which can be flexibly tailored to your needs.

    Also popular now: