core icon indicating copy to clipboard operation
core copied to clipboard

fix: can send Json even if Flight is not started yet

Open pierresh opened this issue 8 months ago • 3 comments

With FlightPHP v2, we could send JSON easily, even if the method start() was not called yet.

Example:

require_once __DIR__ . '/vendor/autoload.php';

Flight::json("Hello");

Now, with v3, nothing happens unless the framework is started with Flight::start() (and it seems requiring router defined, otherwise it returns a 404 error).

This pull request aims to restore the simple behavior of Flight v2 to send a JSON.

pierresh avatar Apr 30 '25 10:04 pierresh

I see that one unit test fails, I will try to solve it.

pierresh avatar Apr 30 '25 12:04 pierresh

So if you want you have a couple options.

https://docs.flightphp.com/en/v3/learn/migrating-to-v3#output-buffering-behavior-3-5-0

You can turn on the old v2 behavior to have it do what you want.

Or you can override the json method to do your bidding or create a new function altogether

https://docs.flightphp.com/en/v3/learn/migrating-to-v3#output-buffering-behavior-3-5-0

// or 'jsonOutputNow'
Flight::map('json', function($data, $status, $flags) {
    header('Content-Type: application/json');
    http_response_code($status);
    echo json_encode($data, $flags);
    exit;
});

n0nag0n avatar May 02 '25 13:05 n0nag0n

Yes, I know, but I feel a bit strange that nothing is sent with Flight::json() in such situation. And I figured out that we have a few customized files which run outside of Flight::start() / Flight::route() for various reasons, thus changing from v2 to v3 is a breaking change.

But it is not a problem if you disagree, we will deal with them one by one.

pierresh avatar May 02 '25 15:05 pierresh

Thanks @krmu for hitting me up on this. Forgot it was still open. I'm thinking through it and I still can't understand why you would want Flight just generate and echo the JSON in a given situation, when you can just create your own function to echo out JSON. The Flight::json() method sets status codes and headers that ultimately will never get sent to the browser. Maybe it is ill named and that's the confusion? I can see that people may think that this is how you use the framework to encode JSON when it should be something more like a flight\util\Json class that encodes the JSON for you. Then you could use that function to encode the JSON and spit it out if you wanted to.......I actually like that idea better and it would solve this PR and there could be other use cases for it.

n0nag0n avatar Jul 20 '25 15:07 n0nag0n

Replaced with https://github.com/flightphp/core/pull/657

n0nag0n avatar Jul 20 '25 15:07 n0nag0n

You can now use echo Json::encode($myVar) to do what you want and it will keep the default flags that the Flight Framework uses to keep your code consistent.

n0nag0n avatar Jul 20 '25 15:07 n0nag0n