Using a composer library in Magento 1, the quick way

Today I had to generate native XLS files from Magento 1. The https://github.com/PHPOffice/PhpSpreadsheet is the best library for the job, but it’s modern in that it uses composer and PSR. Since I really wanted to use this specific package, here is a quick way to include it in the now dated Magento 1 codebase:

First, create an empty directory where the library will be kept:

 

mkdir lib/PhpSpreadsheet
cd PhpSpreadsheet

Then, create a composer.json file:

#lib/PhpSpreadsheet/composer.json
{
  "require": {
    "phpoffice/phpspreadsheet": "~1.3"
  }
}

Then, still in lib/PhpSpreadsheet, let composer download the needed files:

composer install

To actually use the library, we will have to tell Magento how to include the directory in the path and also require the generated composer autoloader. In your helper/model/controller, add a init method to do just that:

protected function initPhpSpreadSheetLib() {
  //Add library directory to include path
  set_include_path(get_include_path() . PATH_SEPARATOR . Mage::getBaseDir('lib') . DS . 'PhpSpreadsheet' . DS . 'vendor');
  //Include composer autoloader
  require_once(Mage::getBaseDir('lib') . DS . 'PhpSpreadsheet' . DS . 'vendor' . DS . 'autoload.php');
}

Then, use the lib. Remember to use fully qualified class names as Magento is not namespace-aware:

$this->initPhpSpreadSheetLib();
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($data,null,'A1');
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($tmpFileName);

Probably there are a million other better ways to achieve the same thing, but this looks like a quick solution to use a library without tinkering with the project’s structure too much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s