naivic / curl
Naivic cURL 封装
1.0.0
2024-09-01 21:57 UTC
Requires
- php: >=8.1
README
一些示例
最简单的 GET 查询 - 从 openlibrary.org 获取书籍信息
$url = "http://openlibrary.org/search.json"; $needle = "Alice Wonderland"; $curl = new \Naivic\CURL(); $res = $curl->query( "GET", $url, [ "q" => $needle ] ); echo "Total time: ".$res->info["total_time"]." sec\n"; echo "Year: ".$res->data["docs"][0]["first_publish_year"]."\n";
结果
Total time: 21.788099 sec
Year: 1889
简单的 REST API - POST、GET、PUT、PATCH、DELETE 查询
使用 https://restful-api.dev/ 来展示功能
让我们准备进行一系列 REST API 请求
$url = "https://api.restful-api.dev/objects"; $hdr = [ "Content-Type: application/json" ]; $hero = [ "name" => "The Cat", "data" => [ "type" => "animal", "location" => "World", ], ]; $curl = new \Naivic\CURL();
好了,现在将“猫”放到世界,并存储服务器响应中的 ID
$res = $curl->query( "POST", $url, $hero, $hdr ); $id = $res->data["id"];
$res->data
Array
(
[id] => ff80818191ad7c2f0191af6b4a550247
[name] => The Cat
[createdAt] => 2024-09-01T21:08:49.883+00:00
[data] => Array
(
[type] => animal
[location] => World
)
)
然后,将“猫”移动到仙境
$hero["data"] = [ "type" => "sapiens", "location" => "Wonderland", ]; $res = $curl->query( "PUT", $url."/".$id, $hero, $hdr );
$res->data
Array
(
[id] => ff80818191ad7c2f0191af6b4a550247
[name] => The Cat
[updatedAt] => 2024-09-01T21:08:51.547+00:00
[data] => Array
(
[type] => sapiens
[location] => Wonderland
)
)
然后... 把“猫”换成爱丽丝!
$res = $curl->query( "PATCH", $url."/".$id, ["name" => "Alice"], $hdr ); print_r( $res->data );
$res->data
Array
(
[id] => ff80818191ad7c2f0191af6b4a550247
[name] => Alice
[updatedAt] => 2024-09-01T21:08:52.623+00:00
[data] => Array
(
[type] => sapiens
[location] => Wonderland
)
)
咚咚咚,唤醒爱丽丝
$res = $curl->query( "DELETE", $url."/".$id, hdr: $hdr );
$res->data
Array
(
[message] => Object with id = ff80818191ad7c2f0191af6b4a550247 has been deleted.
)
爱丽丝在哪里?("谁...是爱丽丝?")
$res = $curl->query( "GET", $url."/".$id, hdr: $hdr );
$res->data
Array
(
[error] => Oject with id=ff80818191ad7c2f0191af6b4a550247 was not found.
)