flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.62k stars 409 forks source link

Question: how to properly download file from the server with FlightPHP #600

Closed pierresh closed 1 month ago

pierresh commented 1 month ago

Hello,

I am sorry for this trivial question, but I wonder what is the cleanest way to download a file from an end-point with FightPHP? I could not see anything related in the documentation. Currently, I am doing as shown below, but in the same way that Symfony has BinaryFileResponse, maybe it would be better to have something similar?

So far

// 1. Retrieve my file $attachment
// 2. Deal with headers

ob_end_clean();
flush();

if (!readfile($attachment)) {
    Flight::error(new Exception('Cannot read file ' . $attachment));
}
n0nag0n commented 1 month ago

Does this example help you out in the streaming portion of the docs? https://docs.flightphp.com/learn/routing#streaming

pierresh commented 1 month ago

Thanks for your quick feedback. I did not know it was possible to stream files :).

Unfortunately, I am using wildcards in my GET router because I have hundreds of routes, so I could not use the callback. I will try to submit a PR for a helper function to download files later this week.

n0nag0n commented 1 month ago

Could you give me a pseudo code example of your codebase and how you're trying to do it? Maybe there's another way?

pierresh commented 1 month ago

Actually, what I wish for is a simple way to handle files, as easy as using Flight::json() for sending a JSON response.

I use a customized Kernel to load Controllers based on the route, so that I do not need to bother with registering all the routes (my app has several hundred). Basically, it looks like this:

Flight::route('GET|POST|PUT|DELETE|PATCH /@module/@name(/@id(/@sub_name(/@line)))', function($module, $name, $id, $sub_name, $line){
    $request = Flight::request();

    $kernel = new App\Kernel();

    $kernel->handle($request);
});

I created a PR for this if you think this idea is interesting.

pierresh commented 1 month ago

As the PR is now merged, I close this issue, thanks.