Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธีสร้าง Web API service ใน PHP


SOAP และ REST APIs เป็น API ที่ใช้กันอย่างแพร่หลาย

พิจารณาคลาส PHP ชื่อ manage.php ช่วยจัดการรายการในฐานข้อมูล:

class manage { private $entryId; function __construct($entryId) {    $this->entryId = $entryId; } function deleteEntry() {    // delete $this->entryId from database }}

บนเซิร์ฟเวอร์ ฟังก์ชันนี้เข้าถึงได้ดังนี้:

require_once('manage.php'); $m = new manage(12); $m->deleteEntry();

เซิร์ฟเวอร์อื่นเข้าถึงได้อย่างไร? สร้างไฟล์ที่สามทำหน้าที่ buffer/interface ช่วยเข้าถึงข้อมูล ตัวอย่าง buffer:

เรียกว่า 'api/delete.php'

require_once('manage.php'); if(hasPermission($_POST['api_key']) {    $m = new manage($_POST['entry_id']);    $m->deleteEntry(); }

ผู้ใช้ส่ง POST request ไปที่ https://example.com/api/delete.php พร้อม api_key และ entry_id