GraphQL 协议的纯 PHP 实现
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.
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:
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
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.
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:
composer self-update)index.php file has been created in the same directory that you have vendor folder in (presumably it's graphql-test folder)php -v)Also, you can always check if script from the examples folder work.
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.
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.
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.
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";
We would recommend to stick to object oriented approach for the several reasons (that matter the most for the GraphQL specifically):
Types reusableWith 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.
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:
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,或尚未同步最近议题。