Welcome Guest, Not a member yet? Register   Sign In
How to exit friendly in my controller
#1
Wink 

I wrote a global function below named outputJson in my project to print JSON and exit.

PHP Code:
/**
 * 格式化Json输出并终止程序
 */
function outputJson($status$msg=''$data=''){
    //header("content-type:application/json");
    \Config\Services::response()->setBody(json_encode(['code'=>$status'msg'=>$msg'data'=>$data]))->send();
    die();



I found a problem when I call PHP native functions "exit/quit" to terminate my program,The rest codes of CI4 framework after running the controller weren't be executed, Such as the After Filter mechanism, Send Response, and Release some instances.
I think calling the exit/quit function to terminate directly my program that is really more convenient than returning recursively in some cases.
Is there any way or more friendly function offered by CI4 Framework to replace exit/quit?
Thanks in advance.
Reply
#2

exit/quit kills PHP runtime imediatley. Basically you should not call in your app it.

And in fact a controller is a class that returns a Response object.

> Is there any way or more friendly function offered by CI4 Framework to replace exit/quit?

What do you want to do?
In your sample code, it seems okay that you just add return and remove die().
Reply
#3

(11-22-2021, 09:03 PM)kenjis Wrote: exit/quit kills PHP runtime imediatley. Basically you should not call in your app it.

And in fact a controller is a class that returns a Response object.

> Is there any way or more friendly function offered by CI4 Framework to replace exit/quit?

What do you want to do?
In your sample code, it seems okay that you just add return and remove die().

That`s a helper function and is one of the many similary cases i mentioned. if i remove die(), then i need to return recursively a response until my controller.
Reply
#4

> if i remove die(), then i need to return recursively a response until my controller.

Unfortunately for you, that is how PHP program works.
Reply
#5

wait php 8.1 , try php fiber (threaded)
Reply




Theme © iAndrew 2016 - Forum software by © MyBB