limoncello-php / app

Quick start JSON API application
MIT License
83 stars 7 forks source link

using 3rd party libraries with Container #32

Open dreamsbond opened 6 years ago

dreamsbond commented 6 years ago

@neomerx i have a use case using the 3rd party libraries PHPExcel for exporting excel sheet(s) currently i have no idea how it could work with the container and non-CRUD routes.

could you give some hints?

neomerx commented 6 years ago

Firstly have a look at a sample

So the easiest would be

public static function configureContainer(LimoncelloContainerInterface $container): void
{
    $container[PHPExcel::class] = function () {
        return new PHPExcel();;
    };
}

then anywhere you can get PHPExcel from container with $container->get(PHPExcel::class)

However much better would be adding an interface specific to your app such as

interface ReportsInterface {
    public function createReportX(string $fileName): ResponseInterface;
    public function createReportY(string $fileName): ResponseInterface;
    // and etc
}

Response is a possible candidate and you should decide which is better for you. I think Response is good because PHPExcel genereates not only content but HTTP headers matter as well.

If you change your mind and start using another reporting engine you will keep ReportsInterface and changes will be localized in Reports class.

So suppose you have an implementation for the interface in Reports class, then

public static function configureContainer(LimoncelloContainerInterface $container): void
{
    $container[ReportsInterface::class] = function (PsrContainerInterface $container) {
        // you can read settings from $container and
        // anything else you need to create Reports
        return new Reports(...);
    };
}
neomerx commented 6 years ago

As far as I can see from this example the only tricky part how can you convert this

header('Content-Disposition: attachment;filename="01simple.xls"');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

into a PSR Response?

This is out of Limoncello scope however my thoughts could be helpful for you: