百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
G

GraphQL

> 后端框架
开源

GraphQL 协议的纯 PHP 实现

702 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

GraphQL 协议的纯 PHP 实现

Looking for Maintainers!

Unfortunatelly, we cannot longer support this package and are looking for someone to take the ownership. Currently Only PRs with bugfixes and not breaking BC are being merged. It's very sad to acknowledge this, but we hope that someone can take it further with the community.

Please, PM @viniychuk if you are interested in taking over.

GraphQL

This is a pure PHP realization of the GraphQL protocol based on the working draft of the official GraphQL Specification located on http://facebook.github.io/graphql/.

GraphQL is a query language for APIs. It brings a new paradigm to the world of client-server communication and delivers a much more predictable behavior and smallest possible over-the-wire responses to any request. GraphQL advanced in many ways and has fundamental quality improvements:

  • strongly typed communication protocol makes both client and server predictable and more stable
  • encourages you to build a constantly evolving APIs and not use versions in the endpoints
  • bulk requests and responses to avoiding waiting for multiple HTTP handshakes
  • easily generated documentation and incredibly intuitive way to explore created API
  • clients will be much less likely to require backend changes

Current package is and will be trying to be kept up to date with the latest revision of the official GraphQL Specification which is now of April 2016.

Symfony bundle is available by the link – http://github.com/Youshido/GraphqlBundle

If you have any questions or suggestions – let's talk on GraphQL Gitter channel

Table of Contents

  • Getting Started
  • Installation
  • Example – Creating Blog Schema
    • Inline approach
    • Object Oriented approach
    • Choosing approach for your project
  • Query Documents
  • Type System
    • Scalar Types
    • Objects
    • Interfaces
    • Enums
    • Unions
    • Lists
    • Input Objects
    • Non-Null
  • Building your schema
    • Abstract type classes
    • Mutation helper class
  • Useful information
    • GraphiQL tool

Getting Started

You should be better off starting with some examples and "Star Wars" become a somewhat "Hello world" for the GraphQL implementations. If you're looking just for that – you can get it via this link – Star Wars example. On the other hand, we prepared a step-by-step guide for those who wants to get up to speed bit by bit.

Installation

Install GraphQL package using composer. If you're not familiar with it, you should check out their manual. Run composer require youshido/graphql.

Alternatively you can run the following commands:

mkdir graphql-test && cd graphql-test
composer init -n
composer require youshido/graphql

Now you're ready to create your GraphQL Schema and check if everything works fine. Your first GraphQL app will be able to receive currentTime request and response with a formatted time string.

you can find this example in the examples directory – 01_sandbox.

Create an index.php file with the following content:

 new ObjectType([
        'name' => 'RootQueryType',
        'fields' => [
            'currentTime' => [
                'type' => new StringType(),
                'resolve' => function() {
                    return date('Y-m-d H:ia');
                }
            ]
        ]
    ])
]));

$processor->processPayload('{ currentTime }');
echo json_encode($processor->getResponseData()) . "\n";

You can now execute php index.php and get a response with your current time:

{
   data: { currentTime: "2016-05-01 19:27pm" }
}

Just like that, you have created a GraphQL Schema with a field currentTime of type String and resolver for it. Don't worry if you don't know what the field, type and resolver mean here, you'll learn along the way.

If you're having any troubles – here're some troubleshooting points:

  • check that you have the latest composer version (composer self-update)
  • make sure your index.php file has been created in the same directory that you have vendor folder in (presumably it's graphql-test folder)
  • last but not least, check that you have php-cli installed and running and it's version >= 5.5 (php -v)

Also, you can always check if script from the examples folder work.

Tutorial – Creating Blog Schema

For our learning example we'll architect a GraphQL Schema for a Blog. You'll probably be using our package along with your favorite framework (we have a Symfony version here), but for the purpose of this tutorial we're keeping it all examples as plain php code.

(Complete example of the Blog schema available by the following link https://github.com/Youshido/GraphQL/tree/master/examples/02_blog)

Our Blog will have Users who can write Posts and leave Comments. Also, there will be a LikePost operation that could be performed by anyone. Let's start with Post. Take a look at the query that returns title and summary of the latest Post:

GraphQL query is a simple text query structured very much similar to the json format.

latestPost {
    title,
    summary
}

Supposedly server should reply with a relevant json response:

{
   data: {
       latestPost: {
           title: "This is a post title",
           summary: "This is a post summary"
       }
   }
}

It looks very simple and straight forward, so let's go ahead and write code that can handle this request.

Creating Post schema

We'll take a quick look on different approaches you can use to define your schema. Each of them has it's own pros and cons, inline approach might seem to be easier and faster when object oriented gives you more flexibility and freedom as your project grows. You should definitely use OOP approach every time you can reuse the type you're creating.

We're going to create RootQueryType with one field latestPost. Every GraphQL Field has a type(e.g. String, Int, Boolean) and it could be of a different kind(e.g. Scalar, Enum, List). You can read more about it in the official documentation, but for now you can think of field of a type like about instance of a class.

Inline approach

You can create inline-index.php file in your project folder and paste the following code there

inline-index.php

…

To check if everything is working – execute inline-index.php: php inline-index.php You should see response as the json encoded object latestPost inside the data section:

{
   data: {
       latestPost: {
           title: "New approach in API has been revealed",
           summary: "In two words - GraphQL Rocks!"
       }
   }
}

Try to play with the code by removing one field from the request or by changing the resolve function.

Object oriented approach

It's a common situation when you need to use the same custom type in different places, so we're going to create a separate class for the PostType and use it in our GraphQL Schema. To keep everything structured we're going to put this and all our future classes into the Schema folder.

Create a file Schema/PostType.php and put the following code in there:

addField('title', new StringType())       // defining "title" field of type String
            ->addField('summary', new StringType());    // defining "summary" field of type String
    }

    public function getName()
    {
        return "Post";  // if you don't do getName – className without "Type" will be used
    }

}

Now let's create the main entry point for this example – index.php:

…

Ensure everything is working properly by running php index.php. You should see the same response you saw for the inline approach.

Next step would be to create a separate class for the latestPostField by extending AbstractField class: Schema/LatestPostField.php

 "New approach in API has been revealed",
            "summary" => "In two words - GraphQL Rocks!",
        ];
    }
}

And now we can update our index.php:

 'RootQueryType',
    'fields' => [
        new LatestPostField()
    ]
]);

$processor = new Processor(new Schema([
    'query' => $rootQueryType
]));
$payload = '{ latestPost { title, summary } }';

$processor->processPayload($payload);
echo json_encode($processor->getResponseData()) . "\n";

Choosing approach for your project

We would recommend to stick to object oriented approach for the several reasons (that matter the most for the GraphQL specifically):

  • makes your Types reusable
  • adds an ability to refactor your schema using IDEs
  • autocomplete to help you avoid typos
  • much easier to navigate through your Schema when project grows

With that being said, we use inline approach a lot to explore and bootstrap ideas or to develop simple fields/resolver that are going to be used in one place only. With the inline approach you can be fast and agile in creating mock-data server to test your frontend or mobile client.

Use valid Names
We highly recommend to get familiar with the official GraphQL Specification Remember that valid identifier in GraphQL should follow the pattern /[_A-Za-z][_0-9A-Za-z]*/. That means any identifier should consist of a latin letter, underscore, or a digit and cannot start with a digit. Names are case sensitive

We'll continue to work on the Blog Schema to explore all essentials details of developing GraphQL server.

Query Documents

In GraphQL terms – query document describe a complete request received by GraphQL service. It contains list of Operations and Fragments. Both are fully supported by our PHP library. There are two types of Operations in GraphQL:

  • Query – a read only request that is not supposed to do any changes on the server
  • Mutation – a request that changes(mutate) data on the server followed by a data fetch

You've already seen examples of Query with latestPost and currentTime, so let's define a simple Mutation that will provide API to Like the Post. Here's sample request and response of likePost mutation:

request

mutation {
  likePost(id: 5)
}

response

{
  data: { likePost: 2 }
}

Any Operation has a response type and in this case the likePost mutation type is Int

Note, that the response type of this mutation is a scalar Int. Of course in real life you'll more likely have a response of type Post for such mutation, but we're going to implement code for a simple example above and even keep it inside index.php:

…

Run php index.php, you should see a valid response:

{"data":{"likePost":2}}

Now, let's make our likePost mutation to return the whole Post as a result. First, we'll add likesCount field to the PostType:

addFields([
            'title'      => new StringType(),
            'summary'    => new StringType(),
            'likesCount' => new IntType()
        ]);
    }

    // Since our class named by a convention, we can remove getName() method
}

Secondly, modify resolve function in LatestPostField:

public function resolve($value, array $args, Resolv

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPgraphqlgraphql-phpgraphql-schema

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架