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:
- composer require os/php-excel
- 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
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 canPHPExcel
.The PHPExcel composer.json contains autoloading information:
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:
force the composer autoloader to be regenerated with
Make sure, vendor/os/php-excel is readable by PHP (compare owner and permissions to core files). Maybe you ran composer require as root?