Learn how YOU can build a Serverless GraphQL API on top of a Microservice architecture with PHP
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!
Disclaimer: This is not a JavaScript vs. PHP rant!
TL;DR
Just show me the Source Code
The big picture
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.
Highlights
Services
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.
GraphQL
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 GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter
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.
… and if you missed it, find the source code at GitHub:
Happy coding!