Simplest possible RPCs in PHP
After spending hours to find out why a particular combination of SoapClient in PHP itself and SOAP::Server from PEAR didn’t consistenly work together (sometimes, arrays passed around lost an arbitrary number of elements), I thought about what would be needed to make RPCs work form a PHP client to a PHP server.
I wanted nothing fancy and I certainly wanted as less an overhead as humanly possible.
This is what I came up with for the server:
This client as shown below is a bit more complex, mainly because it contains some HTTP protocol logic. Logic, which could possibly be reduced to 2-3 lines of code if I’d use the CURL library, but the client in this case does not have the luxury of having access to such functionality.
Also, I’ve already had the function laying around (/me winks at domi), so that’s what I used (as opposed to file_get_contents with a pre-prepared stream context). This way, we DO have the advantage of learning a bit of how HTTP works and we are totally self-contained.
What you can’t pass around this way is objects (at least object which are not of type stdClass) as both client and server would need to have access to the prototype. Also, this seriously lacks error handling. But it generally works much better than what SOAP ever could accomplish.
Naturally, I give up stuff when compared to SOAP or any «real» RPC solution:
- This one works only with PHP
- It has limitations on what data structures can be passed around, though that's aleviated by PHP's incredibly strong array support.
- It relies heavily on PHP's loosely typed nature and thus probably isn't as robust.
Still, protocols like SOAP (or even any protocol with either «simple» or «lightweight» in its name) tend to be so complicated that it’s incredibly hard if not impossible to create different implementations what still correctly work together in all cases.
In my case, where I have the problem of having to separate two pieces of the same application due to unstable third-party libraries which I would not want to have linked into every PHP instance running on that server for which the solution outlined above (plus some error handling code) works better than SOAP on so many levels:
- it's easily debuggable. No need for wireshark or comparable tools
- client and server are written by me, so they are under my full control
- it works all the time
- it relies on as little functionality of PHP as possible and the functionality it depends on is widely used and tested, to I can assume that it's reasonably bug-free (aside of my own bugs).
- it's a whole lot faster than SOAP, though this does not matter at all in this case.
blog comments powered by Disqus