php - How to load Google SDK in Cakephp 3.9

Solution:

I use Google_Client in CakePHP - you shouldn't have to do anything special to use it. If it's installed via composer it's already in Composer's autoloader, you can call it directly.

Ex. In composer.json after running ./composer.phar require google/apiclient:"^2.7" My require section lists the Google API:

"require": {
    "google/apiclient": "^2.7",

Make sure you run ./composer.phar install if it wasn't already installed durring require.

Then in to use the library, I just call it directly, prefixed with \ since it's not namespaced:

public function index()
{
    $client = new \Google_Client();

If you're curious how this works under the hood - Composer will generate all the information it needs to load classes durring require or install and sticks these in several files back in vendor/composer, such as autoload_namespaces.php, where it should automatically have added Google_ to the list there, ex:

<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    // Lots of class prefixes, but eventually:
    'Google_' => array($vendorDir . '/google/apiclient/src'),

Classes that are namespaced to industry standards like PSR-4 (like all modern PHP libs probably should be!) are probably in autoloader_psr4.php - and so on. It registers it's own autoloader in ClassLoader.php, and sticks a reference to this in vendor/autoload.php - which Cake calls essentially on near line 1 of webroot/index.php:

require dirname(__DIR__) . '/vendor/autoload.php';

So in short - you don't need to worry about autoloading again so long as you're working through Composer.

Also - if you're able to use an IDE which helps with autocompletion of class namespaces, like PHPStorm, that might make things easier.

Answer

Solution:

For libraries that specify autoload information, Composer generates a vendor/autoload.php file. You can simply include this file and start using the classes that those libraries provide without any extra work:

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

For more references : https://getcomposer.org/doc/01-basic-usage.md

Source