A few weeks earlier I read a very interesting article from Chris Noring about “Learn how YOU can build a Serverless GraphQL API on top of a Microservice architecture, part 1” which he entirely build with Node.js and Express and I thought to myself: you could do this in PHP and ReactPHP!
As Chris Noring did in his original article, I created two microservices exposing a REST-API, one serving products and another one serving reviews to said products. Those two Microservices will be only available internal and not exposed to the internet, but nevertheless there should be customer facing API. For this purpose I will use GraphQL as a high level API combining the results of the two Services.
As you can imagine, there is nothing original in my article, I just did the same but with PHP and ReactPHP. You can find the source code on GitHub, so I will limit myself to the highlights.
The two services are pretty straight forward. Just a bit of ReactPHP-Code asynchronous handling incoming HTTP-Requests. For the sake of the example both are returning a static JSON-String. In a more in depth example you could connect to a database and look up the data.
When using GraphQL in PHP there are a couple of libraries, but only webonyx/graphql-php seems mature enough, also it has an asynchronous interface supporting ReactPHP. So this was the perfect match for this case.
When using the async-Interface, you need to call
GraphQL::promiseToExecute instead of
GraphQL::executeQuery and give it the promise adapter as a first parameter, which in my case was an instance of
When initialized and used this way the method call to
promiseToExecute will return a ReactPHP Promise, on which you can register your
then-Handler. Also your
resolve-Functions can now return a ReactPHP Promise, which means you can write async code everywhere.
What you get is a pure asynchronous GraphQL-API written in PHP.
Find the source code at GitHub: flow-control/php-graphql-microservice