設計一個PHP文件操作的架構需要考慮多個方面,包括性能、安全性、可維護性和可擴展性。以下是一個基本的架構設計思路:
首先,設計一個清晰的目錄結構,以便于管理和維護代碼。
/project-root
/app
/controllers
/models
/views
/config
database.php
routes.php
/public
index.php
/vendor
/storage
/logs
控制器負責處理用戶請求,調用模型進行數據操作,并返回視圖。
// /app/controllers/UserController.php
namespace App\Controllers;
use App\Models\UserModel;
class UserController {
public function index() {
$userModel = new UserModel();
$users = $userModel->getAllUsers();
require 'views/user/index.php';
}
public function create() {
// Handle user creation logic
}
}
模型負責與數據庫交互,進行數據的增刪改查操作。
// /app/models/UserModel.php
namespace App\Models;
use PDO;
class UserModel {
private $db;
public function __construct() {
$this->connectDB();
}
private function connectDB() {
$config = require 'config/database.php';
$dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
$this->db = new PDO($dsn, $config['username'], $config['password'], $options);
}
public function getAllUsers() {
$stmt = $this->db->query('SELECT * FROM users');
return $stmt->fetchAll();
}
}
配置文件用于存儲數據庫連接信息和路由信息。
// /config/database.php
return [
'host' => 'localhost',
'dbname' => 'mydb',
'username' => 'root',
'password' => '',
];
// /config/routes.php
return [
'user' => 'App\Controllers\UserController',
];
路由負責將URL映射到控制器方法。
// /public/index.php
require 'vendor/autoload.php';
$router = require 'config/routes.php';
$requestMethod = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = trim($uri, '/');
$segments = explode('/', $uri);
$routeFound = false;
$controllerName = '';
$actionName = '';
foreach ($router as $route => $handler) {
$regex = sprintf('#^%s$#', preg_replace('#\s+#', '+', preg_quote($route, '#')));
if (preg_match($regex, $segments)) {
list($controllerName, $actionName) = explode('@', $handler);
$routeFound = true;
break;
}
}
if (!$routeFound) {
header('HTTP/1.0 404 Not Found');
require 'views/error/404.php';
exit();
}
$controllerClass = "App\\Controllers\\{$controllerName}";
$controller = new $controllerClass();
$controller->$actionName();
公共文件用于處理入口文件和加載必要的庫。
// /public/index.php
require 'vendor/autoload.php';
$router = require 'config/routes.php';
$requestMethod = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = trim($uri, '/');
$segments = explode('/', $uri);
$routeFound = false;
$controllerName = '';
$actionName = '';
foreach ($router as $route => $handler) {
$regex = sprintf('#^%s$#', preg_replace('#\s+#', '+', preg_quote($route, '#')));
if (preg_match($regex, $segments)) {
list($controllerName, $actionName) = explode('@', $handler);
$routeFound = true;
break;
}
}
if (!$routeFound) {
header('HTTP/1.0 404 Not Found');
require 'views/error/404.php';
exit();
}
$controllerClass = "App\\Controllers\\{$controllerName}";
$controller = new $controllerClass();
$controller->$actionName();
視圖負責展示數據給用戶。
// /app/views/user/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Users</title>
</head>
<body>
<h1>Users List</h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?php echo htmlspecialchars($user['name']); ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
日志用于記錄應用的運行狀態和錯誤信息。
// /storage/logs/app.log
<?php
$filename = __DIR__ . '/../storage/logs/app.log';
$timestamp = date('Y-m-d H:i:s');
$message = sprintf("[%s] %s\n", $timestamp, $_SERVER['REQUEST_URI']);
file_put_contents($filename, $message, FILE_APPEND);
以上是一個基本的PHP文件操作架構設計,涵蓋了目錄結構、控制器、模型、配置文件、路由、公共文件、視圖和日志等方面。根據具體需求,可以進一步擴展和優化這個架構。