GraphQL PHP Library: webonyx/graphql-php
GraphQL is a modern query language for APIs, developed by Facebook. In PHP, one of the most popular and mature libraries for implementing GraphQL is webonyx/graphql-php. This library allows developers to create flexible, typed, and efficient APIs that give clients the ability to request only the necessary data.
In this article, we will take a detailed look at how to install, configure, and use webonyx/graphql-php in your PHP project. The library fully implements the official GraphQL specification (June 2018) and supports all modern features: queries, mutations, subscriptions, interfaces, unions, and much more.
Installation and Setup
Installation is done via Composer. Open a terminal in the root of your project and run:
composer require webonyx/graphql-phpAfter installation, the library is ready to use. No minimal configuration is required — simply import the necessary classes into your PHP file.
Core Library Components
The library consists of several key components that interact with each other:
- Schema — defines data types and available operations (queries and mutations).
- Types — describe the data structure (ObjectType, ScalarType, EnumType, InterfaceType, UnionType, etc.).
- Resolvers — functions that return data for each field.
- Executor — processes the incoming request and returns the result.
Creating a Simple Schema
Let's look at an example of creating a simple GraphQL schema for working with users. First, define the User type:
<?phpuse GraphQL\\Type\\Definition\\ObjectType;use GraphQL\\Type\\Definition\\Type;
$userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::int(), 'name' => Type::string(), 'email' => Type::string(), 'age' => Type::int(), ],]);Now create the root query type Query, which will return a list of users:
$queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'users' => [ 'type' => Type::listOf($userType), 'resolve' => function ($root, $args) { // Here is usually a database query return [ ['id' => 1, 'name' => 'Ivan Ivanov', 'email' => 'ivan@example.com', 'age' => 30], ['id' => 2, 'name' => 'Maria Petrova', 'email' => 'maria@example.com', 'age' => 25], ]; }, ], 'user' => [ 'type' => $userType, 'args' => [ 'id' => Type::nonNull(Type::int()), ], 'resolve' => function ($root, $args) { // Find user by ID $users = [ 1 => ['id' => 1, 'name' => 'Ivan Ivanov', 'email' => 'ivan@example.com', 'age' => 30], 2 => ['id' => 2, 'name' => 'Maria Petrova', 'email' => 'maria@example.com', 'age' => 25], ]; return $users[$args['id']] ?? null; }, ], ],]);Combining into a Schema and Executing a Query
Now let's combine everything into a single schema and execute a test query:
use GraphQL\\GraphQL;use GraphQL\\Schema;
$schema = new Schema([ 'query' => $queryType,]);
// Incoming GraphQL query (usually comes in POST)$query = '{ users { id name em