当前位置: 首页 > 后端技术 > PHP

在Laravel应用程序中构建GraphQLAPI

时间:2023-03-29 16:38:05 PHP

代码示例:产品列表和用户列表的API示例昨天我们学习了如何在VisualCode中构建Laravel环境,现在让我们学习Facebook的GraphQL。GraphQL是一种用于API的查询语言,也是一种服务器端运行时,可针对您为数据定义的类型系统执行查询。GraphQL不依赖于任何特定的数据库或存储引擎,而是由您的代码和数据提供支持。graphql.orgGraphQL可以提高API调用的灵活性。我们可以像编写数据库查询语句一样请求API获取需要的数据,这对于构建复杂的API查询非常有用。GraphQL还提供了可视化的界面来帮助我们编写查询语句,同时还提供了自动补全的功能,使得编写查询变得更加简单。https://github.com/graphql/gr...从下图可以看出,GraphQL和Rest都运行在业务逻辑层之外:开始1.安装Laravel使用如下命令安装最新版本的Laravel:#在命令行执行composerglobalrequire"laravel/installer"laravelnewlaravel-graphql2。添加GraphQL包使用composer安装graphql-laravel,它提供了很多集成Laravel和GraphQL的功能。3.创建模型如下创建模型和表user_profiles、products、product_images,不要忘记创建模型之间的关系。4.创建查询并定义GraphQL的类型。GraphQL中的查询与RestfulAPI中的结束路径查询相同。查询仅用于获取数据,以及创建、更新和删除操作。我们称之为突变。GraphQL中的类型用于定义查询中每个字段的类型定义。类型会帮助我们对查询结果中的格式化字段进行格式化,比如布尔型、字符串型、浮点型、整型等,还有我们自定义的类型。以下是查询和类型的目录结构:以下是UsersQuery.php和UsersType.php文件的完整源代码:'UsersQuery','description'=>'用户查询'];publicfunctiontype(){//带分页效果的查询结果returnGraphQL::paginate('users');}//过滤查询的参数publicfunctionargs(){return['id'=>['name'=>'id','type'=>Type::int()],'email'=>['name'=>'email','type'=>Type::string()]];}publicfunctionresolve($root,$args,SelectFields$fields){$where=function($query)use($args){if(isset($args['id'])){$query->where('id',$args['id']);}if(isset($args['email'])){$query->where('email',$args['email']);}};$user=User::with(array_keys($fields->getRelations()))->where($where)->select($fields->getSelect())->paginate();返回$用户;}}'Users','description'=>'Atype','model'=>User::class,//定义用户类型的数据模型];//定义字符段的类型publicfunctionfields(){return['id'=>['type'=>Type::nonNull(Type::int()),'description'=>'用户的id'],'email'=>['type'=>Type::string(),'description'=>'用户邮箱'],'name'=>['type'=>Type::string(),'description'=>'Thenameoftheuser'],//数据模型中的关联字段'user_profiles'user_profiles=>['type'=>GraphQL::type('user_profiles'),'description'=>'用户的个人资料']];}protectedfunctionresolveEmailField($root,$args){returnstrtolower($root->email);}}写完查询和类型后,我们需要编辑config/graphql。php文件将查询语句和类型注册到Schema中'graphql','routes'=>'query/{graphql_schema?}','controllers'=>\Rebing\GraphQL\GraphQLController::class。'@query','middleware'=>[],'default_schema'=>'default',//注册查询命令'schemas'=>['default'=>['query'=>['users'=>UsersQuery::class,'products'=>ProductsQuery::class,],'mutation'=>[],'middleware'=>[]],],//注册类型'types'=>['product_images'=>ProductImagesType::class,'products'=>ProductsType::class,'user_profiles'=>UserProfilesType::class,'users'=>UsersType::class,],'error_formatter'=>['\Rebing\GraphQL\GraphQL','formatError'],'params_key'=>'params'];5.测试我们可以很简单的使用GraphiQL来写查询语句,因为写的时候可以自动补全,也可以使用postman请求API,下面是自动补全的例子:下面是查询结果的例子如果想查看源码,可以访问以下地址:)https://github.com/ardani/lar...转自PHP/Laravel开发者社区https://laravel-china.org/top。..