首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 編寫簡單 App 接口實戰:從環境搭建到 GET/POST 接口開發與 iOS 對接測試

     編輯:PHP 綜合知識

開發環境搭建

Mac 推薦:MAMP Pro

  • 集成 Apache + MySQL + PHP
  • 圖形化虛擬主機管理
  • 支持多 PHP 版本切換

輕量級替代:內建 Apache + PHP + Homebrew MySQL

# 啟用 Apache
sudo apachectl start

# 配置 PHP (macOS 內建)
# 編輯 /etc/apache2/httpd.conf 取消註釋 LoadModule php7_module

# 安裝 MySQL
brew install mysql
brew services start mysql

虛擬主機配置示例

# /etc/apache2/extra/httpd-vhosts.conf

    ServerName api.local
    DocumentRoot "/Users/username/Sites/api"
    
        AllowOverride All
        Require all granted
    

編輯 /etc/hosts 添加 127.0.0.1 api.local

第一個 GET 接口

<?php
// api.local/index.php
header('Content-Type: application/json; charset=utf-8');

$data = [
    'tid' => 100,
    'name' => '標哥的技術博客',
    'site' => 'www.huangyibiao.com'
];

$response = [
    'code' => 200,
    'message' => 'success',
    'data' => $data,
    'timestamp' => time(),
];

echo json_encode($response, JSON_UNESCAPED_UNICODE);

瀏覽器測試

curl https://api.local/
# {"code":200,"message":"success","data":{"tid":100,"name":"標哥的技術博客","site":"www.huangyibiao.com"},"timestamp":1699999999}

POST 接口與參數驗證

<?php
header('Content-Type: application/json; charset=utf-8');

$type = isset($_POST['type']) ? (int)$_POST['type'] : 0;

$response = ['code' => 200, 'message' => 'success', 'data' => null];

if ($type < 1 || $type > 2) {
    $response = ['code' => 400, 'message' => 'type 參數無效,需為 1 或 2', 'data' => null];
    http_response_code(400);
    exit(json_encode($response, JSON_UNESCAPED_UNICODE));
}

switch ($type) {
    case 1:
        $response['data'] = [
            'type' => 1,
            'name' => '標哥的技術博客',
            'site' => 'www.huangyibiao.com'
        ];
        break;
    case 2:
        $response['data'] = [
            'type' => 2,
            'name' => '公眾號:標哥的技術博客',
            'site' => 'weixin search: biaogedejishuboke'
        ];
        break;
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);

curl 測試 POST

curl -X POST -d "type=1" https://api.local/
# {"code":200,"message":"success","data":{"type":1,"name":"標哥的技術博客","site":"www.huangyibiao.com"},"timestamp":1699999999}

iOS 客戶端對接示例

使用 HYBNetworking 庫

// GET
NSString *url = @"https://api.local/";
[HYBNetworking getWithUrl:url refreshCache:YES success:^(id response) {
    NSLog(@"GET 成功: %@", response);
    // response 已自動解析為 NSDictionary
} fail:^(NSError *error) {
    NSLog(@"GET 失敗: %@", error);
}];

// POST
NSDictionary *params = @{@"type": @(1)};
[HYBNetworking postWithUrl:url refreshCache:YES params:params success:^(id response) {
    NSLog(@"POST 成功: %@", response);
} fail:^(NSError *error) {
    NSLog(@"POST 失敗: %@", error);
}];

原生 URLSession 實現

// GET
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"https://api.local/"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) { NSLog(@"Error: %@", error); return; }
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"Response: %@", json);
}];
[task resume];

// POST
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.local/"]];
req.HTTPMethod = @"POST";
req.HTTPBody = [@"type=1" dataUsingEncoding:NSUTF8StringEncoding];
[[NSURLSession sharedSession] dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // 同樣解析...
}].resume();

接口開發最佳實踐棧

層面建議工具/庫
路由分發單入口 + 路由表FastRoute, 框架內建
參數驗證專用驗證器類Respect/Validation, illuminate/validation
異常處理統一 try-catch + 友好錯誤碼Whoops (開發), 自定義異常體系
日誌記錄結構化日誌 + 請求IDMonolog, Laravel Log
限流熔斷Redis 滑動窗口 + SentinelPredis + 自定義中間件
文檔生成OpenAPI 3.0 註解swagger-php, 屬性註解
測試單元 + 集成 + 壓測PHPUnit, Postman, k6

從「寫死數據」到「真實業務」的演進

  1. 靜態數組返回(本文示例)
  2. 連接 MySQL 讀取數據
  3. 引入 Model/Repository 層分離邏輯
  4. 接入 Redis 緩存熱點數據
  5. 拆分微服務,API 網關統一入口

總結

本文演示了從零搭建 PHP 接口服務、編寫 GET/POST 接口、定義統一響應格式、iOS 客戶端對接的完整流程。**核心不在於語言,而在於:統一協議、嚴格驗證、可觀測性、文檔先行**。建議新項目直接使用 Laravel / Hyperf / ThinkPHP 6 等現代框架,享受開箱即用的路由、驗證、中間件、ORM、測試等能力,專注業務邏輯而非輪子構建。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved