Serving GraphQL Subscriptions Using PHP and Drupal

Rate this content
Bookmark

Most people in the GraphQL Galaxy are familiar with JavaScript tools when creating GraphQL servers.


But what do you do if your team’s speciality is PHP and you have all your existing data available in a Drupal based platform?

In this session I’ll take you on a tour of the tools we used to build a PHP based service that handles GraphQL subscriptions powering Open Social’s Real-Time chat, and how you can use our learnings for your own project.

This talk has been presented at GraphQL Galaxy 2021, check out the latest edition of this Tech Conference.

FAQ

OpenSocial is a community engagement platform that helps organizations connect with their communities online and grow them in the process. It is built on top of the Drupal content management framework.

OpenSocial chose GraphQL to add a real-time chat feature to allow quicker communication between members on their platforms. GraphQL facilitates efficient communication between the server and client.

The chat feature was built using Rescript, React, and GraphQL. The Urql GraphQL client was used on the client side.

The GraphQL PHP library is used in Drupal. It is a PHP port of the JavaScript reference implementation and supports queries, mutations, and subscriptions.

Drupal handles individual requests through a web server like Apache or Nginx, which closes the connection and clears the memory after generating a response. This short-lived model does not support the persistent connections required for GraphQL subscriptions.

OpenSocial introduced a message queue using RebitMQ and the Bunny library for ReactPHP. When a new chat message is sent, it notifies the subscription server of new data, which then executes a GraphQL query and sends the result to the client.

The message queue, implemented using RebitMQ, notifies the subscription server of new data. This allows the subscription server to execute a GraphQL query for the client and send the result back, delivering the chat message.

ReactPHP and AMP are the libraries used for writing asynchronous code. OpenSocial settled on ReactPHP after trying both.

Rachet, a WebSocket server for ReactPHP, was chosen to handle WebSocket connections.

A service that can handle persistent connections between the client and the web server is required. This service can be written in various languages, but OpenSocial chose to use PHP with ReactPHP for their subscription service.

Alexander Varwijk
Alexander Varwijk
7 min
10 Dec, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Lightning Talk discusses the setup of GraphQL subscriptions in a Drupal-based product, using Rescript and React on the client-side and the Urql GraphQL client. The choice of ReactPHP over AMP for the subscription service is explained, highlighting the use of Fibers in PHP 8.1 for asynchronous task handling.

1. Setting up GraphQL Subscriptions in Drupal

Short description:

In this Lightning Talk, I will explain how we set up GraphQL subscriptions for an existing Drupal-based product. We wanted to add a real-time chat feature to our platform using GraphQL and integrate it with our existing member and group structure. We chose Rescript and React for the client-side and the Urql GraphQL client. The GraphQL PHP library, a PHP port of the JavaScript reference implementation, was the best choice for working with GraphQL in Drupal. However, Drupal's short-lived model posed limitations for subscriptions, requiring an additional service to handle persistent connections.

Hey, GraphQL Galaxy. In this Lightning Talk, I want to take you through what it took to set up GraphQL subscriptions for an existing Drupal-based product. I'm Alexander Farweg or Kingdutch on places like Twitter and GitHub, and I'm the Lead Frontend Engineer and GraphQL Initiative Lead at OpenSocial.

OpenSocial is a community engagement platform that helps organizations connect with their communities online and grow them in the process. OpenSocial is built on top of the Drupal content management framework. To allow quicker communication between members on our platforms, we wanted to use GraphQL to add a real-time chat as a new feature to our existing products. The goal was for the chat to integrate with our existing member and group structure. To build our chats, we chose Rescript and React. And of course, GraphQL to let our server and client communicate. On the client side, we chose the excellent Urql GraphQL client.

In PHP, there are a few libraries that can help you with GraphQL. The best choice in my opinion, and the one used in Drupal, is the GraphQL PHP library. This is a PHP port of the JavaScript reference implementation. I'm a big fan of the library structure. It makes porting new GraphQL features to PHP very easy. For example, one of my first contributions was implementing interfaces extending other interfaces. To achieve this, I could almost copy and paste the JavaScript tests and implementation word-for-word.

Just replacing a bit of the syntax. Drupal itself works with modules that allow you to create a site by bundling together functionality. The Drupal community has provided an excellent Drupal module that utilizes GraphQL-PHP and lets developers easily expose Drupal's data storage as a GraphQL API. As you would expect, queries and mutations work out of the box. The GraphQL-PHP library also supports subscriptions, and the Drupal-GraphQL module does not impose any limitations on defining subscriptions in your schema or resolving them. However, when trying to make GraphQL subscriptions in a framework such as Drupal, we run into some of its limitations. Drupal, like other popular PHP content management systems, such as WordPress, handle individual requests through a web server like Apache or Nginx. This means that once a response to a request is generated, the connection is closed and the memory is cleared for the next request. This short-lived model doesn't work for subscriptions which require a persistent connection and the ability to send data to the client without the client requesting it. This means we need additional service to sit between our client and our web server to handle these persistent connections. We can write these servers in many different languages, such as JavaScript, Rescript, OCaml, Rust or your other favorite language. However, since I was working with an existing team and product, it was important to look at the skills that were already present in our organization. I had to make sure that whatever was built would also be maintainable by others.

2. Choosing ReactPHP for Subscription Service

Short description:

Since OpenSocial's back-end developers are most familiar with PHP, we decided to use it for our subscription service. ReactPHP was chosen over AMP for its syntax and the introduction of Fibers in PHP 8.1. This allowed us to create a long-running PHP process and perform tasks asynchronously.

Or I would risk having to maintain it all by myself. With this in mind, since OpenSocial's back-end developers are most familiar with PHP, we decided to use this for our subscription service too. This does mean that we need some new tools. We now need something that can create a long-running PHP process, and perform tasks asynchronously. There are a few libraries out there already that can help us with this. ReactPHP and AMP are both capable libraries that let you write asynchronous code. The biggest difference is what syntax they use for their promises. Fun fact, the PHP extension for an event loop that both ReactPHP and AMP use actually predates Node.js. More recently, ReactPHP and AMP have bundled their forces to build Revolt, which will make use of Fibers, a feature that has been introduced in PHP 8.1. At OpenSocial, we settled on ReactPHP after trying both it and AMP.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
Envelope is a powerful GraphQL plugin system that simplifies server development and allows for powerful plugin integration. It provides conformity for large corporations with multiple GraphQL servers and can be used with various frameworks. Envelope acts as the Babel of GraphQL, allowing the use of non-spec features. The Guild offers GraphQL Hive, a service similar to Apollo Studio, and encourages collaboration with other frameworks and languages.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
The Talk discusses the challenges and advancements in using GraphQL and React together. It introduces RedwoodJS, a framework that simplifies frontend-backend integration and provides features like code generation, scaffolding, and authentication. The Talk demonstrates how to set up a Redwood project, generate layouts and models, and perform CRUD operations. Redwood automates many GraphQL parts and provides an easy way for developers to get started with GraphQL. It also highlights the benefits of Redwood and suggests checking out RedwoodJS.com for more information.
Adopting GraphQL in an Enterprise
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
Adopting GraphQL in an Enterprise
Today's Talk is about adopting GraphQL in an enterprise. It discusses the challenges of using REST APIs and the benefits of GraphQL. The Talk explores different approaches to adopting GraphQL, including coexistence with REST APIs. It emphasizes the power of GraphQL and provides tips for successful adoption. Overall, the Talk highlights the advantages of GraphQL in terms of efficiency, collaboration, and control over APIs.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced 2022React Advanced 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura