0
votes

So I have the Paypal REST API installed ( https://github.com/paypal/rest-api-sdk-php ) with Composer in my_drupal_module/lib/Drupal/ and now I want to use the namespaces in a function in my module. I understood that I need something like xautoload ( https://drupal.org/project/xautoload ) to do that so I tried something like:

$payer = new \Drupal\vendor\PayPal\Api\Payer;

with and without the first slash, and with and without parentheses at the end but it didn't work. I added:

require DIR . '/lib/Drupal/vendor/autoload.php';

but still nothing so I commented it. Meanwhile I found this: https://drupal.org/node/1976206 that explains this issue but it is unclear to me what exactly to write in hook_xautoload() or direct registration for the setup that I have. Can someone please help?

3

3 Answers

1
votes

Nevermind. I solved it. Thanks to proloy03 who gave me the idea: https://drupal.org/node/2096621

You don't need xautoload to load the classes and namespace just implement hook_init to require it like so:

function my_module_init() {
    require __DIR__ . '/vendor/autoload.php';
}

and then in your function write:

$payer = new PayPal\Api\Payer();

and it all works.

1
votes

With xautload you can do something like this...

In mymodule.module

function mymodule_libraries_info() {

'paypal' => array(
      'name' => 'PayPal SDK',
      'xautoload' => function($adapter) {
       $adapter->composerJson('composer.json'); 
     }
}

Declaring this allow you to use the namespace. Like

use PayPal\Api\Amount;

Check xautoload.api.php

0
votes

Your assumption that you need XAutoload to use the Paypal API installed by Composer is wrong.

The only thing you need to make any code installed by Composer available is to include the Composer autoloader in your code execution path when you need any of the provided classes. The easiest form of this is to simply require the Composer autoloader in the very first index.php (or whatever Drupal uses) file that answers every request (possibly instantiating more Drupal classes, modules and stuff).

Once the code execution comes to your own code, the autoloading allows your code to include all the classes you included with Composer.

How to use the code? Don't invent your own namespace for the existing code, it will not work. "\Drupal\vendor\PayPal\Api\Payer" sounds pretty wrong to me, I suspect the correct namespace is "\PayPal\Api\Payer". And yes, that file does indeed exist. So you have to use that.

If it still does not work, complaining the class could not be loaded, then the Composer autoloader file is not included in your scripts code path.