laravel graphql php,結合 Laravel 初步學習 GraphQL

e8c8b6f7726a4edb5b250fa14679d429.png

本文字數:7134,大概需要14.27分鐘。

aac66848ebb2e24e62f5cb54d3d085c4.png

按照官網所述的:

A query language for your API一種用于 API 的查詢語言

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

GraphQL 既是一種用于 API 的查詢語言也是一個滿足你數據查詢的運行時。 GraphQL 對你的 API 中的數據提供了一套易于理解的完整描述,使得客戶端能夠準確地獲得它需要的數據,而且沒有任何冗余,也讓 API 更容易地隨著時間推移而演進,還能用于構建強大的開發者工具。

主要有以下幾個特點:

請求你所要的數據不多不少。向你的 API 發出一個 GraphQL 請求就能準確獲得你想要的數據,不多不少。 GraphQL 查詢總是返回可預測的結果。

獲取多個資源只用一個請求。GraphQL 查詢不僅能夠獲得資源的屬性,還能沿著資源間引用進一步查詢。典型的 REST API 請求多個資源時得載入多個 URL,而 GraphQL 可以通過一次請求就獲取你應用所需的所有數據。這樣一來,即使是比較慢的移動網絡連接下,使用 GraphQL 的應用也能表現得足夠迅速。

描述所有的可能類型系統。GraphQL API 基于類型和字段的方式進行組織,而非入口端點。你可以通過一個單一入口端點得到你所有的數據能力。GraphQL 使用類型來保證應用只請求可能的數據,還提供了清晰的輔助性錯誤信息。應用可以使用類型,而避免編寫手動解析代碼。

API 演進無需劃分版本。給你的 GraphQL API 添加字段和類型而無需影響現有查詢。老舊的字段可以廢棄,從工具中隱藏。通過使用單一演進版本,GraphQL API 使得應用始終能夠使用新的特性,并鼓勵使用更加簡潔、更好維護的服務端代碼。

使用你現有的數據和代碼。GraphQL 讓你的整個應用共享一套 API,而不用被限制于特定存儲引擎。GraphQL 引擎已經有多種語言實現,通過 GraphQL API 能夠更好利用你的現有數據和代碼。你只需要為類型系統的字段編寫函數,GraphQL 就能通過優化并發的方式來調用它們。

Demo

先寫一個 Demo 來看看如何結合 Laravel 使用 GraphQL。

引入 rebing/graphql-laravel

composer require "rebing/graphql-laravel"

因為 Laravel 5.5 開始,有「包自動發現」http://mp.weixin.qq.com/s/AD05BiKjPsI2ehC-mhQJQw功能,所以 Laravel 5.5 可以不用手動引入該 provider 和 aliase。之前的版本需要引入對應的 provider 和 aliase。

"extra": { ? ?"laravel": { ? ? ? ?"providers": [ ? ? ? ? ? ?"Rebing\\GraphQL\\GraphQLServiceProvider" ? ? ? ?], ? ? ? ?"aliases": { ? ? ? ? ? ?"GraphQL": "Rebing\\GraphQL\\Support\\Facades\\GraphQL" ? ? ? ?} ? ?}}

創建 Type 和 Query

Type: 通過 Type,可以幫助我們格式化查詢結果的類型,主要有 boolean、string、float、int 等,同時也可以自定義類型

Query: 通過 Query,可以獲取我們需要的數據。

在項目根目錄創建 GraphQL 文件件用于存放 Type 和 Query

671f0e51046b15753b4d66169d1b84c6.png

定義 UsersType:

<?php /** * User: yemeishu */namespace App\GraphQL\Type;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Type as GraphQLType;classUsersTypeextendsGraphQLType{ ? ?protected $attributes = [ ? ? ? ?'name' => 'Users', ? ? ? ?'description' => 'A type', ? ? ? ?'model' => User::class, // define model for users type ? ?]; ? ?// define field of type ? ?public functionfields(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::int()), ? ? ? ? ? ? ? ?'description' => 'The id of the user' ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'type' => Type::string(), ? ? ? ? ? ? ? ?'description' => 'The email of user' ? ? ? ? ? ?], ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'type' => Type::string(), ? ? ? ? ? ? ? ?'description' => 'The name of the user' ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?protected functionresolveEmailField($root, $args){ ? ? ? ?return strtolower($root->email); ? ?}}

定義 Query:

<?php /** * User: yemeishu */namespace App\GraphQL\Query;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Query;use Rebing\GraphQL\Support\SelectFields;classUsersQueryextendsQuery{ ? ?protected $attributes = [ ? ? ? ?'name' => 'users', ? ? ? ?'description' => 'A query of users' ? ?]; ? ?public functiontype(){ ? ? ? ?return Type::listOf(GraphQL::type('users')); ? ?} ? ?// arguments to filter query ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'name' => 'id', ? ? ? ? ? ? ? ?'type' => Type::int() ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'name' => 'email', ? ? ? ? ? ? ? ?'type' => Type::string() ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($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']); ? ? ? ? ? ?} ? ? ? ?}; ? ? ? ?$users = User::with(array_keys($fields->getRelations())) ? ? ? ? ? ?->where($where) ? ? ? ? ? ?->select($fields->getSelect()) ? ? ? ? ? ?->get(); ? ? ? ?return $users; ? ?}}

配置 graphql.php

將寫好的 UsersType 和 UsersQuery 注冊到 GraphGL 配置文件中。

3b2b694d42350545351ede48286b58b0.png

測試

我們主要有兩種途徑用于測試,第一種就是向測試 RESTful 接口一樣,使用 Postman:

5ce1405021326c7af7d8766b90faf266.png

另一種方式就是利用 GraphiQL:

An in-browser IDE for exploring GraphQL.https://github.com/graphql/graphiql

這里我們使用noh4ck/graphiql

// 1. 安裝插件composer require "noh4ck/graphiql:@dev"// 2. 加入 providerGraphiql\GraphiqlServiceProvider::class// 3. 命令artisan graphiql:publish

配置文件可看出 route 為:/graphql-ui

701b251c461e35ff04e5a4a578f73d9b.png

運行結果:

32630840a8c8c1240fdfea50e5ab78d5.png

還可以通過傳入參數 (id: 1) 來篩選數據:

32efa426663102b8641748ddfd8490c5.png

Mutation

通過 Demo,我們初步了解 GraphQL 的 Query 查詢方法,接下來我們看看 Mutation 的用法。

如果說 Query 是 RESTful 的「查」,那么 Mutation 充當的作用就是「增、刪、改」了。

cf7e10ccb57a1c0cafdd457b7a96d8cf.png

在 GraphQL 文件夾下創建「Mutation」文件夾,存放和 Mutation 相關的類。

Create Mutation Class

<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classNewUserMutationextendsMutation{ ? ?protected $attributes = [ ? ? ? ?'name' => 'NewUser' ? ?]; ? ?public functiontype(){ ? ? ? ?return GraphQL::type('users'); ? ?} ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'name' => 'name', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?], ? ? ? ? ? ?'email' => [ ? ? ? ? ? ? ? ?'name' => 'email', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?], ? ? ? ? ? ?'password' => [ ? ? ? ? ? ? ? ?'name' => 'password', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($root, $args){ ? ? ? ?$args['password'] = bcrypt($args['password']); ? ? ? ?$user = User::create($args); ? ? ? ?if (!$user) { ? ? ? ? ? ?return null; ? ? ? ?} ? ? ? ?return $user; ? ?}}

Update Mutation Class

<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classUpdateUserMutationextendsMutation{ ? ?protected $attributes = [ ? ? ? ?'name' => 'UpdateUser' ? ?]; ? ?public functiontype(){ ? ? ? ?return GraphQL::type('users'); ? ?} ? ?public functionargs(){ ? ? ? ?return [ ? ? ? ? ? ?'id' => [ ? ? ? ? ? ? ? ?'name' => 'id', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::int()) ? ? ? ? ? ?], ? ? ? ? ? ?'name' => [ ? ? ? ? ? ? ? ?'name' => 'name', ? ? ? ? ? ? ? ?'type' => Type::nonNull(Type::string()) ? ? ? ? ? ?] ? ? ? ?]; ? ?} ? ?public functionresolve($root, $args){ ? ? ? ?$user = User::find($args['id']); ? ? ? ?if (!$user) { ? ? ? ? ? ?return null; ? ? ? ?} ? ? ? ?$user->name = $args['name']; ? ? ? ?$user->save(); ? ? ? ?return $user; ? ?}}

配置 graphql.php

把 NewUserMutation 和 UpdateUserMutation 加入 graphql mutation 配置中

0e10bb45713b83fa63c7bcf392dc9ac8.png

測試

421130b56969f81ef1c6fe8c7afefc0a.png

如上圖,創建兩個 mutation,可以選擇任意一個看運行效果。

創建一個 User:

893147d10f87f3257f7c2457217cd5bf.png

更新「id: 1」用戶信息:

65696c1476f058766be876b04697dd78.png

其中在 graphql-ui 界面,右上角還可以看到「Docs」,點開可以查看這兩個 mutiation 的說明:

5cec3dca4cfa3ed3f1a79155f5c0208d.png

總結

通過簡單的「增改查」User 來初步了解 GraphQL 的 Query 和 Mutation 的使用,接下來可以將 GraphQL 作為微服務的「網關」層的前一層來使用。

「未完待續」

coding01 期待您繼續關注

2a9d61e8a9a5d60c64d4b78e4faec4a4.gif

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279041.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279041.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279041.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

wi-fi共享大師免廣告_如何保護Wi-Fi網絡免受入侵

wi-fi共享大師免廣告Insecure Wi-Fi is the easiest way for people to access your home network, leech your internet, and cause you serious headaches with more malicious behavior. Read on as we show you how to secure your home Wi-Fi network. 不安全的Wi-Fi是人們…

MongoDb分片集群認證

本文主要基于已經搭建好的未認證集群&#xff0c;結合上篇Mongodb副本集分片集群模式環境部署&#xff08;https://www.cnblogs.com/woxingwoxue/p/9875878.html&#xff09;&#xff0c; MongoDb分片集群認證幾個主要流程1.在分片集群環境中&#xff0c;副本集內成員之間需要用…

漢克爾變換matlab,HankelTransform

HankelTransform所屬分類&#xff1a;matlab例程開發工具&#xff1a;matlab文件大小&#xff1a;135KB下載次數&#xff1a;66上傳日期&#xff1a;2011-09-17 13:41:39上 傳 者&#xff1a;甜頭說明&#xff1a; Matlab Hankel變換源代碼&#xff0c;可以直接當做MATLAB too…

【材質】色彩基礎

RBG顏色空間 目前&#xff0c;絕大部分顯示器采用的是RGB顏色標準&#xff0c;因此幾乎所有軟件也采用此標準&#xff0c;UE4也不例外。 R、G、B這三個字母分別代表紅色&#xff08;red&#xff09;、綠色&#xff08;green&#xff09;、藍色&#xff08;blue&#xff09;三條…

使用mintty(_如何使用Mintty改善Cygwin控制臺

使用mintty(Cygwin’s great for getting some Linux command-line goodness in Windows, but using the Windows Shell to access it kills some of that magic. Using Mintty and a few other methods, you can make the experience much more luxurious. Cygwin非常適合在Wi…

18.phpmyadmin 4.8.1 遠程文件包含漏洞(CVE-2018-12613)

phpmyadmin 4.8.1 遠程文件包含漏洞&#xff08;CVE-2018-12613&#xff09; phpMyAdmin是一套開源的、基于Web的MySQL數據庫管理工具。其index.php中存在一處文件包含邏輯&#xff0c; 通過二次編碼即可繞過檢查&#xff0c;造成遠程文件包含漏洞。 受影響版本: phpMyAdmin 4.…

開源php面板,寶塔面板nginx安裝終于搞定了

server{listen 80;server_name lvyou.yssknet.com;index index.php index.html index.htm default.php default.htm default.html;root ***********/public;#SSL-START SSL相關配置&#xff0c;請勿刪除或修改下一行帶注釋的404規則#error_page 404/404.html;#SSL-END#ERROR-PA…

[Erlang 0004] Centos 源代碼編譯 安裝 Erlang

由于最終部署的生產環境是Centos&#xff0c;所以我需要在Centos中安裝Erlang B13R04 &#xff0c;第一次做這件事情破費周折&#xff0c;主要是對Erlang依賴的庫不熟悉&#xff0c;總是編譯不過&#xff1b;這里梳理一下安裝過程中的細節&#xff1a; Erlang依賴哪些庫&#x…

關于“Python”的核心知識點整理大全38

14.1.1 創建 Button 類 由于Pygame沒有內置創建按鈕的方法&#xff0c;我們創建一個Button類&#xff0c;用于創建帶標簽的實心矩形。 你可以在游戲中使用這些代碼來創建任何按鈕。下面是Button類的第一部分&#xff0c;請將這個類保存為 文件button.py&#xff1a; button.py …

同步您的Google Chrome書簽,主題等

Do you regularly use Google Chrome on multiple computers? Here’s how you can keep almost everything in your browser synced easily in Google Chrome. 您是否經常在多臺計算機上使用Google Chrome&#xff1f; 您可以通過以下方法在Google Chrome瀏覽器中輕松同步瀏…

Python中函數的參數傳遞與可變長參數

轉自旭東的博客原文 Python中函數的參數傳遞與可變長參數 Python中傳遞參數有以下幾種類型&#xff1a; &#xff08;1&#xff09;像C一樣的默認缺省函數 &#xff08;2&#xff09;根據參數名傳參數 &#xff08;3&#xff09;可變長度參數 示例如下&#xff1a; &#xff08…

matlab的plot沒有反應,用plot畫圖沒有反應

本帖最后由 躺著看雨 于 2018-6-7 10:35 編輯0.0854232732222489 -1.47227270375083e-08 17.0844721322814 17.08465464444980.0854232767446789 -1.41282430199396e-08 17.0844728367686 17.08465534893580.0854232802671089 …

轉]MATLAB 與 C 語言的接口

MATLAB 到 C 語言程序的轉換可以由兩種途徑完成&#xff0c;其一是 MATLAB 自己提供的 C 語言翻譯程序 mcc, 另一種是原第 3 方公司 MathTools 開發的 MATCOM。后者出現較早&#xff0c;功能遠比 MATLAB 自己的翻譯程序強大&#xff0c;所以 MathTools 公司已經被 MathWorks 公…

找call寫call_如何將Google Call Widget添加到任何網頁

找call寫callAdding a Google Call Widget to your website or blog allows visitors to contact you using your Google Voice number. The widget provides an easy and cost-effective way to provide live customer support without the customer knowing your real number…

XML與web開發-01- 在頁面顯示和 XML DOM 解析

前言&#xff1a; 關于 xml 特點和基礎知識&#xff0c;可以菜鳥教程進行學習&#xff1a;http://www.runoob.com/xml/xml-tutorial.html 本系列筆記&#xff0c;主要介紹 xml 在 web 開發時需要了解的知識 XML 在頁面顯示數據 XML 指可擴展標記語言&#xff08;eXtensible Mar…

酷安應用市場php源碼,酷安應用市場 v11.0.3-999 去廣告極限精簡版

酷安&#xff0c;真實有趣的數碼社區。酷安app&#xff0c;國內安卓應用市場客戶端&#xff0c;應用資源豐富&#xff0c;應用開發者水準高&#xff0c;應用無首發Logo&#xff0c;原汁原味上架&#xff0c;得到了安卓用戶群廣泛認可。有人說現在的酷安市場(酷安網)沒有以前那么…

再戰android-語音識別2(修改配置)

可怕的半桶水一直在晃。程序中需要根據用戶的選擇設置語音識別的語言&#xff08;目前科大訊飛支持英文、普通話、粵語&#xff09;&#xff0c;不想每次要用戶去IatSetting中去改&#xff0c;需要能直接修改IatSetting的設置。之前移植的IatSetting頁面沒有細究&#xff0c;直…

chromebook刷機_如何將網站添加到您的Chromebook架子上

chromebook刷機Bookmarks are great to keep your favorite sites nearby, but they aren’t the fastest option out there. Instead, why not add shortcuts for your favorite websites right on the Chromebook shelf? 書簽可以很好地將您喜歡的網站保留在附近&#xff0c…

php判斷外鏈,php檢查字符串中是否有外鏈的方法

這篇文章主要介紹了php檢查字符串中是否有外鏈的方法,涉及php針對字符串的正則匹配的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下本文實例講述了php檢查字符串中是否有外鏈的方法。分享給大家供大家參考。具體實現方法如下&#xff1a;/*** is_external_link 檢測字符…

【經驗分享】產品、運營人如何告別重復的數據分析工作?

我是一名互聯網的運營打雜MM&#xff0c;除了每天繁忙的工作&#xff0c;每周、每月的數據匯報也是我頭疼的東東。因為本身我不聰明&#xff0c;數學也不是太好&#xff0c;對數據不那么愛&#xff0c;而且還要做數據分析&#xff0c;對于我這種數據小白分分鐘崩潰。每周、每月…