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. #[Controller]
  11. class GraphQLController
  12. {
  13. /**
  14. * @var Schema
  15. */
  16. #[Inject]
  17. protected $schema;
  18. #[PostMapping(path: "/graphql")]
  19. public function test(RequestInterface $request)
  20. {
  21. $rawInput = $request->getBody()->getContents();
  22. $input = json_decode($rawInput, true);
  23. $query = $input['query'];
  24. $variableValues = isset($input['variables']) ? $input['variables'] : null;
  25. return GraphQL::executeQuery($this->schema, $query, null, null, $variableValues)->toArray();
  26. }
  27. #[Query]
  28. public function hello(string $name): string
  29. {
  30. return $name;
  31. }
  32. }

查询:

  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. #[Type]
  6. class Product
  7. {
  8. protected $name;
  9. protected $price;
  10. public function __construct(string $name, float $price)
  11. {
  12. $this->name = $name;
  13. $this->price = $price;
  14. }
  15. #[Field]
  16. public function getName(): string
  17. {
  18. return $this->name;
  19. }
  20. #[Field]
  21. public function getPrice(): ?float
  22. {
  23. return $this->price;
  24. }
  25. }

GraphQLController 中加入

  1. <?php
  2. use App\Model\Product;
  3. use Hyperf\GraphQL\Annotation\Query;
  4. #[Query]
  5. public function product(string $name, float $price): Product
  6. {
  7. return new Product($name, $price);
  8. }

查询:

  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 的文档。