Load external php library in custom module I’ve read a lot of topic on this but i can’t figure why it is not working for me.

I’ve built a custom module. It is working fine since return $output; in my controller class is working : I can see in front-end a page with my custom html.

I’ve written a script outside Drupal in order to test. Basically, i connect to a webervice and retrieve all the datas. It’s working fine.

Now, i want to execute that script inside the controller class.

I need to load an external php library to instantiate an object.

In my test php file (outside Drupal) a simple require_once is working.

require_once('nusoap.php');


But it is not working in my controller class.

So, i’ve activated the library module and do :

$path = libraries_get_path('nusoap') . DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php';

require($path);


It’s still not working. 

Error message indiquactes :


  Error: Class 'Drupal\webservices_dc\nusoap_client' not found


I’m sur the file path is correct because if i do this, i can see the content of the file.

echo file_get_contents(DRUPAL_ROOT . '/modules/contrib/webservices_tr/webservices_dc/src/Controller/nusoap.php');
die();


I’ve also tried this :

in nusoap.php (where there is the class i need to include),  

namespace Drupal\webservices_dc;


and in module controller class :

use Drupal\webservices_dc\nusoap_client;


But it is still not working.

Finally, i’ve copied the content of the external php library inside the module controller and it is working.

So i’m nearly sure the issue is related to the loading of that external library.

What is the correct way to load external php library (and wait it is fully loaded) in order to use it in a custom module ?
You cannot require classes with require or library hooks. Nor should you be editing external packages.

You are supposed to require external php packages with Composer. Composer will update the autoloader. Then in your class, you can say:

use ExternalPackage\namespace\Foo;

In the header and Foo class is then usable. Furthermore, you can inject it to the constructor with a little more work.

I would advise using SoapClient instead of nusoap as that is very old.

Regarding SoapClient, here is something I solved recently injecting it proper to my class, because that's the same road you're heading down.

Dependency inject a class with values from a config object?