Magento 2 – How to Use Non-Namespace Libraries

magento2

I am trying to use a third party library in my Magento 2 module which I include via composer:
https://packagist.org/packages/os/php-excel

This extension isn't using namespaces and it seems that it raise some autoloading conflicts with Magento 2 when I try to use it in my own module.

What I tried first:

  1. composer require os/php-excel
  2. tried to use a static method from this library in one of my models:
    \PHPExcel_IOFactory::load($file);

Receiving the error:

Source class  "\PHPExcel_IO" for "PHPExcel_IOFactory" generation does not exist.

What I tried #2:

I have added the \PHPExcel object (which it seems that's the API object which allows you to use the features from this library ) as a parameter in my __construct():

namespace Fsu\Import\Model;

use Magento\Framework\Filesystem\Directory\ReadFactory as DirReadFactory;
use Magento\Framework\Filesystem\File\ReadFactory as FileReadFactory;

class Importer {

    /** @var  bool */
    protected $_dryRun;

    /** @var  string */
    protected $_path;

    /** @var \Magento\Framework\Filesystem\Directory\ReadFactory */
    protected $_directoryReader;

    /** @var \Magento\Framework\Filesystem\File\ReadFactory */
    protected $_fileReader;


    public function __construct(
        DirReadFactory $directoryReader, 
        FileReadFactory $fileReader, 
        \PHPExcel $excel //this is the object I am trying to use with DI
    )
    {
        $this->_directoryReader = $directoryReader;
        $this->_fileReader      = $fileReader;
        $this->_excelParser     = $excel;
    }

    //....
}

But I receive this error:

[ReflectionException]
Class PHPExcel does not exist

So do you think such libraries can be used with Magento 2 ? And what is the proper way to do it ?

Context:
I am writing a new cli command which to be used to import products and the import data is stored in .xsl files.

Thank you !

Best Answer

Source class "\PHPExcel_IO" for "PHPExcel_IOFactory" generation does not exist.

You see this error message because Magento assumes, all nonexistent classes that end with "Factory" should be automatically generated. So as you inferred correctly, it's an autoloading problem: PHPExcel_IOFactory cannot be autoloaded, neither can PHPExcel.

The PHPExcel composer.json contains autoloading information:

"autoload": {
    "psr-0": {
        "PHPExcel": "PHPExcel"
    },
    "files": ["PHPExcel.php"]
}

With that, both variants you tried, should work: using the class directly and via dependency injection. The problem is not that the classes are not namespaced - autoloading vendor libraries is handled well by composer!

What you can try:

  1. force the composer autoloader to be regenerated with

    composer dump-autoload
    
  2. Make sure, vendor/os/php-excel is readable by PHP (compare owner and permissions to core files). Maybe you ran composer require as root?

Related Topic