Preconditions

Composer is installed.

Installation

To install the library in the local development environment:

  1. In terminal, navigate (cd) to the project root directory.

  2. Run the following command:

composer require google/apiclient:^2.15.0

Change 2.15.0 to the latest version of the library.

  1. This will install all Google APIs services that are included in this library. By navigating to /project-root/vendor/google/apiclient-services/src, we can see all of the services that were installed. To keep only the services that we’re actually going to use, edit the composer.json file in the project root directory.

  2. Add the pre-autoload-dump script and the list of required services (google/apiclient-services) so it looks similar to this:

{
    "require": {
        "google/apiclient": "^2.15.0"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "Sheets"
        ]
    }
}

In the example above, we keep only the Google Drive and Google Sheets services.

  1. Run the following command to apply the changes:
composer update
  1. Include the autoloader where the API service is used:
require_once '/project-root/vendor/autoload.php';

On a WordPress site:

require_once ABSPATH . 'vendor/autoload.php';

Add a new Google API service

If we need to expand the list of API services previously defined in google/apiclient-services:

  1. Add the new service name to the google/apiclient-services list in the composer.json file.

  2. In terminal, navigate (cd) to the project root directory.

  3. Run:

rm -r vendor/google/apiclient-services
  1. Run:
composer update

If we don’t know the name of the new service

  1. We can temporarily remove the pre-autoload-dump line and the google/apiclient-services list from composer.json.
  2. In terminal, navigate (cd) to the project root directory.
  3. Run:
rm -r vendor/google/apiclient-services
  1. Run:
composer update
  1. All Google API services will be installed.
  2. Navigate to /project-root/vendor/google/apiclient-services/src.
  3. Find there the new service that is needed and copy its name.
  4. Restore the composer.json file (re-add the pre-autoload-dump line and the google/apiclient-services list).
  5. Add the new service name to the google/apiclient-services list.
  6. Run:
composer update

Installation in production

You can learn more about how I install the PHP dependencies on the production server in my other post.

References