基于PHP8和MySQL的安全稳定可扩展API开发架构设计

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

不使用第三方框架,基于PHP8,设计一个安全稳定可复用可扩展的API开发架构。基于mysql

回答:

设计一个安全、稳定、可复用和可扩展的API开发架构是一个复杂的任务,尤其是在不使用第三方框架的情况下。以下是一个基于PHP8和MySQL的API开发架构的设计思路:

目录结构

首先,定义一个清晰的目录结构:

/api
    /config
        config.php
        database.php
    /controllers
        UserController.php
    /models
        User.php
    /core
        Router.php
        Controller.php
        Model.php
        Request.php
        Response.php
        Database.php
    /middlewares
        AuthMiddleware.php
    /helpers
        functions.php
    /public
        index.php
    /logs
        error.log
    /tests
        UserTest.php

配置文件

/config/config.php 中存储应用的基本配置:

<?php
return [
    'app_name' => 'MyAPI',
    'base_url' => 'http://localhost/api',
    'log_file' => __DIR__ . '/../logs/error.log',
];

/config/database.php 中存储数据库配置:

<?php
return [
    'host' => 'localhost',
    'dbname' => 'mydatabase',
    'username' => 'root',
    'password' => '',
];

数据库连接

/core/Database.php 中创建一个数据库连接类:

<?php

namespace Core;

use PDO;
use PDOException;

class Database
{
    private static $instance = null;
    private $connection;

    private function __construct()
    {
        $config = require __DIR__ . '/../config/database.php';
        try {
            $this->connection = new PDO(
                "mysql:host={$config['host']};dbname={$config['dbname']}",
                $config['username'],
                $config['password']
            );
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            error_log($e->getMessage(), 3, __DIR__ . '/../logs/error.log');
            die('Database connection error');
        }
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getConnection()
    {
        return $this->connection;
    }
}

基础模型

/core/Model.php 中创建一个基础模型类:

<?php

namespace Core;

class Model
{
    protected $db;

    public function __construct()
    {
        $this->db = Database::getInstance()->getConnection();
    }
}

用户模型

/models/User.php 中创建一个用户模型类:

<?php

namespace Models;

use Core\Model;
use PDO;

class User extends Model
{
    public function getAllUsers()
    {
        $stmt = $this->db->query("SELECT * FROM users");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getUserById($id)
    {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->execute(['id' => $id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
}

基础控制器

/core/Controller.php 中创建一个基础控制器类:

<?php

namespace Core;

class Controller
{
    protected function jsonResponse($data, $statusCode = 200)
    {
        header('Content-Type: application/json');
        http_response_code($statusCode);
        echo json_encode($data);
        exit;
    }
}

用户控制器

/controllers/UserController.php 中创建一个用户控制器类:

<?php

namespace Controllers;

use Core\Controller;
use Models\User;

class UserController extends Controller
{
    public function index()
    {
        $userModel = new User();
        $users = $userModel->getAllUsers();
        $this->jsonResponse($users);
    }

    public function show($id)
    {
        $userModel = new User();
        $user = $userModel->getUserById($id);
        if ($user) {
            $this->jsonResponse($user);
        } else {
            $this->jsonResponse(['message' => 'User not found'], 404);
        }
    }
}

路由

/core/Router.php 中创建一个简单的路由类:

<?php

namespace Core;

class Router
{
    private $routes = [];

    public function add($method, $path, $handler)
    {
        $this->routes[] = compact('method', 'path', 'handler');
    }

    public function dispatch($method, $path)
    {
        foreach ($this->routes as $route) {
            if ($route['method'] === $method && $route['path'] === $path) {
                list($controller, $action) = explode('@', $route['handler']);
                $controller = "Controllers\\$controller";
                if (class_exists($controller) && method_exists($controller, $action)) {
                    call_user_func_array([new $controller, $action], []);
                    return;
                }
            }
        }
        http_response_code(404);
        echo json_encode(['message' => 'Not Found']);
    }
}

请求和响应

/core/Request.php/core/Response.php 中创建请求和响应类:

<?php

namespace Core;

class Request
{
    public static function method()
    {
        return $_SERVER['REQUEST_METHOD'];
    }

    public static function path()
    {
        $path = $_SERVER['REQUEST_URI'] ?? '/';
        $queryString = $_SERVER['QUERY_STRING'] ?? '';
        if ($queryString) {
            $path = str_replace('?' . $queryString, '', $path);
        }
        return $path;
    }
}
<?php

namespace Core;

class Response
{
    public static function json($data, $statusCode = 200)
    {
        header('Content-Type: application/json');
        http_response_code($statusCode);
        echo json_encode($data);
        exit;
    }
}

中间件

/middlewares/AuthMiddleware.php 中创建一个简单的认证中间件:

<?php

namespace Middlewares;

class AuthMiddleware
{
    public static function handle()
    {
        // 简单的示例,实际应用中应使用更复杂的认证逻辑
        if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
            http_response_code(401);
            echo json_encode(['message' => 'Unauthorized']);
            exit;
        }
    }
}

入口文件

/public/index.php 中设置入口文件:

<?php

require __DIR__ . '/../vendor/autoload.php';

use Core\Router;
use Core\Request;
use Middlewares\AuthMiddleware;

$router = new Router();

// 定义路由
$router->add('GET', '/users', 'UserController@index');
$router->add('GET', '/users/{id}', 'UserController@show');

// 认证中间件
AuthMiddleware::handle();

// 分发请求
$router->dispatch(Request::method(), Request::path());

自动加载

使用 Composer 的自动加载功能来自动加载类。在项目根目录下创建 composer.json 文件:

{
    "autoload": {
        "psr-4": {
            "Core\\": "core/",
            "Controllers\\": "controllers/",
            "Models\\": "models/",
            "Middlewares\\": "middlewares/"
        }
    }
}

然后运行 composer dump-autoload 生成自动加载文件。

日志记录

/helpers/functions.php 中创建一个简单的日志记录函数:

<?php

function log_error($message)
{
    $config = require __DIR__ . '/../config/config.php';
    error_log($message, 3, $config['log_file']);
}

测试

/tests/UserTest.php 中创建一个简单的测试文件:

<?php

use PHPUnit\Framework\TestCase;
use Models\User;

class UserTest extends TestCase
{
    public function testGetAllUsers()
    {
        $userModel = new User();
        $users = $userModel->getAllUsers();
        $this->assertIsArray($users);
    }

    public function testGetUserById()
    {
        $userModel = new User();
        $user = $userModel->getUserById(1);
        $this->assertIsArray($user);
    }
}

结论

以上是一个简单的API开发架构,基于PHP8和MySQL,且不使用第三方框架。这个架构包括了基本的目录结构、配置文件、数据库连接、模型、控制器、路由、中间件、请求和响应处理、日志记录和测试。这个架构是可扩展的,可以根据需要添加更多的功能和模块。