php
use GraphQL\GraphQL;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\FieldConfig;
class UserType {
public function __construct($id, $name) {
$this-id = $id;
$this-name = $name;
}
}
class QueryType {
private $users = [
new UserType(1, 'Alice'),
new UserType(2, 'Bob'),
new UserType(3, 'Charlie'),
// 更多用户...
];
public function resolveUsers($root, $args) {
return $this-users;
}
public function resolveUser($root, $args) {
return $this-findById($args['id']);
}
private function findById($id) {
foreach ($this-users as $user) {
if ($user-id === $id) {
return $user;
}
}
return null;
}
}
3、创建GraphQL Schema
接下来,创建一个GraphQL Schema来定义你的查询和字段。
php
use GraphQL\GraphQL;
use GraphQL\Type\Definition\Schema;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ArgumentType;
use GraphQL\Type\Definition\InputObjectType;
use GraphQL\Type\Definition\ObjectType;
class UserInputType extends InputObjectType {
public function __construct() {
parent::__construct([
'name' = Type::string(),
]);
}
}
class PaginationArgsType extends InputObjectType {
public function __construct() {
parent::__construct([
'first' = ArgumentType::new()-type(Type::int()),
'last' = ArgumentType::new()-type(Type::int()),
'after' = ArgumentType::new()-type(Type::string()),
'before' = ArgumentType::new()-type(Type::string()),
]);
}
}