I have built a REST API in PHP that, in several cases, uses an exit() statement to prevent the script from continuing for various reasons.
This works well when I’ve been making calls to it using a JavaScript fetch.
I have now come across a case where I need to use this API in a PHP file on the same server. I know that I could use ‘include’, but this means that if an exit() statement is triggered, my entire script will stop running.
My API is quite extensive and so I’d prefer not to make edits to it (I know that I could replace exit with return for instance, but many of the exits in my API are called inside functions meaning that a return wouldn’t have the desired effect.)
Is there a better way to access my API in PHP than include? Or some way to get around this? Thank you.
>Solution :
You could treat it as an API and make a HTTP request to it using curl_exec or file_get_contents – that way you’d get basically the same experience as you do if you call it via fetch in your JS. It’s a little bit less efficient than a direct include (because a HTTP request has a network overhead), but it avoids any refactoring and lets you treat it as a separate component or service, rather than something which needs integrating into other PHP scripts.
Obviously for more flexibility you’d refactor it so it has two interfaces, with shared business logic. So one bit is a class which performs the core functionality and you can instantiate it and call functions on it to get things done. Then the other bit is specifically to process incoming HTTP requests and respond to them – obviously it would make use of the separate class when needed in order to perform specific tasks. And if you have the class in a separate file, you could then just include that in other PHP scripts and use its functions directly without going via the web interface.