不使用第三方框架,基于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
/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',
];
/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;
}
}
/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";
}
}
/core/Controller.php
<?php
namespace Core;
class Controller
{
protected function view($view, $data = [])
{
extract($data);
require "../app/Views/{$view}.php";
}
}
/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();
}
}
/core/View.php
<?php
namespace Core;
class View
{
public static function render($view, $data = [])
{
extract($data);
require "../app/Views/{$view}.php";
}
}
/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);
/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]);
}
}
/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();
}
}
/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>
/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
/composer.json
{
"autoload": {
"psr-4": {
"Core\\": "core/",
"App\\": "app/"
}
}
}
运行 composer dump-autoload
生成自动加载文件。
以上是一个简单的PHP API框架的基础结构。您可以根据需要扩展和优化这个框架,例如添加中间件、错误处理、日志记录、单元测试等功能。这个框架的设计目的是提供一个清晰的代码结构和基本的功能,便于扩展和维护。