在ThinkPHP框架中集成GraphQL,需要进行以下几个步骤:
overblog/graphql-bundle
包。composer require overblog/graphql-bundle
overblog/graphql-bundle
。在 config/services.yaml
文件中添加以下内容:
services:
Overblog\GraphQLBundle\Request\Parser\ParserInterface:
alias: Overblog\GraphQLBundle\Request\Parser\Parser
Overblog\GraphQLBundle\Error\ErrorHandler:
public: true
Overblog\GraphQLBundle\Error\ErrorHandlerInterface:
alias: Overblog\GraphQLBundle\Error\ErrorHandler
Overblog\GraphQLBundle\Executor\Executor:
public: true
Overblog\GraphQLBundle\Executor\ExecutorInterface:
alias: Overblog\GraphQLBundle\Executor\Executor
在 config/routes.yaml
文件中添加以下内容:
graphql:
path: /graphql
methods: [POST]
defaults:
_controller: 'overblog_graphql.request.controller::requestAction'
在 src/GraphQL/Type
目录下创建类型文件,例如 UserType.php
:
<?php
namespace App\GraphQL\Type;
use GraphQL\Type\Definition\Type;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* @GQL\Type
*/
class UserType
{
/**
* @GQL\Field(type="ID!")
*/
public function id()
{
return '1';
}
/**
* @GQL\Field(type="String!")
*/
public function name()
{
return 'John Doe';
}
/**
* @GQL\Field(type="Int!")
*/
public function age()
{
return 30;
}
}
在 src/GraphQL/Query
目录下创建查询文件,例如 UserQuery.php
:
<?php
namespace App\GraphQL\Query;
use App\GraphQL\Type\UserType;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* @GQL\Query
*/
class UserQuery
{
/**
* @GQL\Field(type="[UserType!]!")
*/
public function users()
{
return [
new UserType(),
new UserType(),
new UserType(),
];
}
}
在 GraphQL 的路由 config/routes.yaml
文件中,使用 query
参数指定查询类,例如:
graphql:
path: /graphql
methods: [POST]
defaults:
_controller: 'overblog_graphql.request.controller::requestAction'
query: 'App\GraphQL\Query\UserQuery'
在浏览器中访问 http://your-project-url/graphql
,就可以看到 GraphQL 接口了。在 GraphQL 接口中使用查询,例如:
query {
users {
id
name
age
}
}
这样就可以从 GraphQL 接口中查询用户信息了。
注意:在使用 overblog/graphql-bundle
时,需要使用注解来配置 GraphQL 的类型和查询。详细的注解使用方法可以查看 overblog/graphql-bundle
官方文档。