CodeIgniter Forums
How to exit friendly in my controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: How to exit friendly in my controller (/showthread.php?tid=80620)



How to exit friendly in my controller - yongplus - 11-22-2021

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.


RE: How to exit friendly in my controller - kenjis - 11-22-2021

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().


RE: How to exit friendly in my controller - yongplus - 11-23-2021

(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.


RE: How to exit friendly in my controller - kenjis - 11-23-2021

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

Unfortunately for you, that is how PHP program works.


RE: How to exit friendly in my controller - ikesela - 11-23-2021

wait php 8.1 , try php fiber (threaded)