基于PHP8和MySQL构建多应用API框架的详细指南

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

不使用第三方框架,基于PHP8和mysql,DIY一个稳定安全,代码逻辑清晰可复用和可扩展的多应用API框架

回答:

创建一个稳定、安全、代码逻辑清晰、可复用和可扩展的多应用API框架是一个复杂的任务,但我们可以从基础开始,逐步构建一个简单的框架。以下是一个基本的框架结构,您可以根据需要进行扩展和优化。

目录结构

/my-api-framework
    /app
        /Controllers
        /Models
        /Views
    /config
        config.php
    /core
        Router.php
        Controller.php
        Model.php
        View.php
        Database.php
    /public
        index.php
    /vendor
    .htaccess
    composer.json

1. 配置文件

/config/config.php

<?php

return [
    'db' => [
        'host' => 'localhost',
        'dbname' => 'your_database',
        'user' => 'your_username',
        'password' => 'your_password',
    ],
    'base_url' => 'http://localhost/my-api-framework/public',
];

2. 数据库连接

/core/Database.php

<?php

namespace Core;

use PDO;
use PDOException;

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

    private function __construct($config)
    {
        try {
            $this->connection = new PDO(
                "mysql:host={$config['host']};dbname={$config['dbname']}",
                $config['user'],
                $config['password']
            );
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }

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

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

3. 路由器

/core/Router.php

<?php

namespace Core;

class Router
{
    private $routes = [];

    public function add($route, $callback)
    {
        $this->routes[$route] = $callback;
    }

    public function dispatch($uri)
    {
        foreach ($this->routes as $route => $callback) {
            if ($route === $uri) {
                return call_user_func($callback);
            }
        }
        http_response_code(404);
        echo "404 Not Found";
    }
}

4. 控制器基类

/core/Controller.php

<?php

namespace Core;

class Controller
{
    protected function view($view, $data = [])
    {
        extract($data);
        require "../app/Views/{$view}.php";
    }
}

5. 模型基类

/core/Model.php

<?php

namespace Core;

use Core\Database;

class Model
{
    protected $db;

    public function __construct()
    {
        $config = require '../config/config.php';
        $this->db = Database::getInstance($config['db'])->getConnection();
    }
}

6. 视图基类

/core/View.php

<?php

namespace Core;

class View
{
    public static function render($view, $data = [])
    {
        extract($data);
        require "../app/Views/{$view}.php";
    }
}

7. 公共入口文件

/public/index.php

<?php

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

use Core\Router;

$router = new Router();

$router->add('/', function() {
    echo "Welcome to the API";
});

$router->add('/users', function() {
    $controller = new \App\Controllers\UserController();
    $controller->index();
});

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($uri);

8. 用户控制器示例

/app/Controllers/UserController.php

<?php

namespace App\Controllers;

use Core\Controller;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $userModel = new User();
        $users = $userModel->getAllUsers();
        $this->view('users/index', ['users' => $users]);
    }
}

9. 用户模型示例

/app/Models/User.php

<?php

namespace App\Models;

use Core\Model;

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

10. 用户视图示例

/app/Views/users/index.php

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h1>Users</h1>
    <ul>
        <?php foreach ($users as $user): ?>
            <li><?php echo htmlspecialchars($user['name']); ?></li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

11. .htaccess 文件

/.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

12. Composer 自动加载

/composer.json

{
    "autoload": {
        "psr-4": {
            "Core\\": "core/",
            "App\\": "app/"
        }
    }
}

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

结论

以上是一个简单的PHP API框架的基础结构。您可以根据需要扩展和优化这个框架,例如添加中间件、错误处理、日志记录、单元测试等功能。这个框架的设计目的是提供一个清晰的代码结构和基本的功能,便于扩展和维护。