Magento – Include external PHP library in Magento 2 module

3rd-party-librarymagento-2.0magento2module

I am trying to include an external PHP library inside my Magento 2 module, specifically the eKomi PHP library (https://github.com/ekomi-dev/ekomi-api).

I have added the PHP files into the module so the folder structure looks like:

MyName
  MyModule
    Ekomi
      Request
        ..
      Service
        ..
      Api.php
    etc
      ..
    Helper
      ..
    composer.json
    registration.php

My composer.json file looks like this:

{
  "name": "MyName/MyModule",
  "description": "N/A",
  "require": {
    "php": "~5.5.22|~5.6.0|~7.0.0"
  },
  "type": "magento2-module",
  "version": "1.0.0",
  "license": [
    "OSL-3.0",
    "AFL-3.0"
  ],
  "autoload": {
    "files": [
      "registration.php"
    ],
    "psr-4": {
      "Magento\\Catalog\\": "",
      "Ekomi\\": "Ekomi/"
    }
  }
}

When I run php bin/magento setup:di:compile I am getting PHP include errors inside my Ekomi directory, I do not think I am including the files correctly inside my composer.json file.

The error message:

Compilation was started.
Proxies code generation... 0/7 [>---------------------------]   0% 1 sec 46.0 Mi
Proxies code generation... 1/7 [====>-----------------------]  14% 1 sec 50.0 Mi
Repositories code generation... 1/7 [====>-----------------------]  14% 1 sec 500 MiB
PHP Fatal error:  Class 'Ekomi\Request\AbstractRequest' not found in /var/www/magento2/app/code/MyName/MyModule/Ekomi/Request/GetProduct.php on line 8

Best Answer

There's zero reason to complicate something simple, unless you want to use composer's features at the cost of overhead of using coding for it. My library isn't even on composer and I don't want to leap through hoops to just include the library so this is simple and 2 steps, using library foo as an example.

1) put the library folder in lib/internal/ making it lib/internal/foo

2) in a module you have, put this in registration.php

require_once(BP.'/lib/internal/foo/include.php');

That's it, it works and won't mess up setup:di:compile. You can now use that library in your module. Obviously include.php has to exist and be the file that will load all your libraries code, some it might be index.php, or autoload.php

Related Topic