GraphQL

GraphQL 组件对 thecodingmachine/graphqlite 进行抽象。

安装

  1. composer require hyperf/graphql

快速开始

简单查询

  1. <?php
  2. namespace App\Controller;
  3. use GraphQL\GraphQL;
  4. use GraphQL\Type\Schema;
  5. use Hyperf\Di\Annotation\Inject;
  6. use Hyperf\GraphQL\Annotation\Query;
  7. use Hyperf\HttpServer\Annotation\Controller;
  8. use Hyperf\HttpServer\Annotation\PostMapping;
  9. use Hyperf\HttpServer\Contract\RequestInterface;
  10. /**
  11. * @Controller()
  12. */
  13. class GraphQLController
  14. {
  15. /**
  16. * @Inject()
  17. * @var Schema
  18. */
  19. protected $schema;
  20. /**
  21. * @PostMapping(path="/graphql")
  22. */
  23. public function test(RequestInterface $request)
  24. {
  25. $rawInput = $request->getBody()->getContents();
  26. $input = json_decode($rawInput, true);
  27. $query = $input['query'];
  28. $variableValues = isset($input['variables']) ? $input['variables'] : null;
  29. return GraphQL::executeQuery($this->schema, $query, null, null, $variableValues)->toArray();
  30. }
  31. /**
  32. * @Query()
  33. */
  34. public function hello(string $name): string
  35. {
  36. return $name;
  37. }
  38. }

查询:

  1. {
  2. hello(name: "graphql")
  3. }

响应:

  1. {
  2. "data": {
  3. "hello": "graphql"
  4. }
  5. }

类型映射

  1. <?php
  2. namespace App\Model;
  3. use Hyperf\GraphQL\Annotation\Type;
  4. use Hyperf\GraphQL\Annotation\Field;
  5. /**
  6. * @Type()
  7. */
  8. class Product
  9. {
  10. protected $name;
  11. protected $price;
  12. public function __construct(string $name, float $price)
  13. {
  14. $this->name = $name;
  15. $this->price = $price;
  16. }
  17. /**
  18. * @Field()
  19. */
  20. public function getName(): string
  21. {
  22. return $this->name;
  23. }
  24. /**
  25. * @Field()
  26. */
  27. public function getPrice(): ?float
  28. {
  29. return $this->price;
  30. }
  31. }

GraphQLController 中加入

  1. <?php
  2. use App\Model\Product;
  3. /**
  4. * @Query()
  5. */
  6. public function product(string $name, float $price): Product
  7. {
  8. return new Product($name, $price);
  9. }

查询:

  1. {
  2. hello(name: "graphql")
  3. product(name: "goods", price: 156.5) {
  4. name
  5. price
  6. }
  7. }

响应:

  1. {
  2. "data": {
  3. "hello": "graphql",
  4. "product": {
  5. "name": "goods",
  6. "price": 156.5
  7. }
  8. }
  9. }

更多使用方法可以查看 GraphQLite 的文档。