PHP项目如何搭建基础框架?

wen PHP项目 15

本文目录导读:

PHP项目如何搭建基础框架?

  1. 项目目录结构设计
  2. 核心框架文件
  3. 使用示例
  4. Composer 配置 (composer.json)
  5. 使用 composer 安装
  6. 完整框架功能完善
  7. 最佳实践建议

我来为您详细介绍PHP项目基础框架的搭建方法。

项目目录结构设计

首先创建清晰的项目目录结构:

myproject/
├── app/                    # 应用核心目录
│   ├── Controllers/       # 控制器
│   ├── Models/            # 模型
│   ├── Views/             # 视图
│   ├── Config/            # 配置文件
│   └── Helpers/           # 辅助函数
├── public/                # 公共访问目录
│   ├── index.php          # 入口文件
│   ├── css/               # 样式文件
│   ├── js/                # JavaScript文件
│   └── uploads/           # 上传目录
├── vendor/                # 第三方库(Composer)
├── storage/               # 存储文件
│   ├── logs/              # 日志文件
│   └── cache/             # 缓存文件
└── .htaccess              # URL重写配置

核心框架文件

入口文件 (public/index.php)

<?php
// 定义基础路径
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');
// 自动加载
require_once BASE_PATH . '/vendor/autoload.php';
// 加载配置
$config = require APP_PATH . '/Config/app.php';
// 错误处理
error_reporting(E_ALL);
ini_set('display_errors', $config['debug']);
// 启动路由
$router = new App\Core\Router();
$router->dispatch($_SERVER['REQUEST_URI']);

配置文件 (app/Config/app.php)

<?php
return [
    'debug' => true,
    'url' => 'http://localhost:8000',
    'database' => [
        'host' => 'localhost',
        'name' => 'myproject',
        'user' => 'root',
        'pass' => '',
        'charset' => 'utf8mb4'
    ]
];

路由类 (app/Core/Router.php)

<?php
namespace App\Core;
class Router {
    protected $routes = [];
    public function get($uri, $handler) {
        $this->routes['GET'][$uri] = $handler;
        return $this;
    }
    public function post($uri, $handler) {
        $this->routes['POST'][$uri] = $handler;
        return $this;
    }
    public function dispatch($uri) {
        $method = $_SERVER['REQUEST_METHOD'];
        $uri = parse_url($uri, PHP_URL_PATH);
        if (isset($this->routes[$method][$uri])) {
            $handler = $this->routes[$method][$uri];
            list($controller, $action) = explode('@', $handler);
            $controller = "App\\Controllers\\{$controller}";
            $instance = new $controller();
            return call_user_func([$instance, $action]);
        }
        throw new \Exception('404 Not Found');
    }
}

控制器基类 (app/Core/Controller.php)

<?php
namespace App\Core;
class Controller {
    protected function view($view, $data = []) {
        extract($data);
        $viewPath = APP_PATH . "/Views/{$view}.php";
        if (file_exists($viewPath)) {
            require $viewPath;
        }
    }
    protected function json($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
    protected function redirect($url) {
        header("Location: {$url}");
        exit;
    }
}

数据库类 (app/Core/Database.php)

<?php
namespace App\Core;
class Database {
    protected static $instance = null;
    protected $pdo;
    private function __construct() {
        $config = require APP_PATH . '/Config/app.php';
        $db = $config['database'];
        try {
            $this->pdo = new \PDO(
                "mysql:host={$db['host']};dbname={$db['name']};charset={$db['charset']}",
                $db['user'],
                $db['pass']
            );
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch (\PDOException $e) {
            die("Database connection failed: " . $e->getMessage());
        }
    }
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function query($sql, $params = []) {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
    public function fetchAll($sql, $params = []) {
        return $this->query($sql, $params)->fetchAll(\PDO::FETCH_ASSOC);
    }
    public function fetch($sql, $params = []) {
        return $this->query($sql, $params)->fetch(\PDO::FETCH_ASSOC);
    }
}

使用示例

创建控制器 (app/Controllers/HomeController.php)

<?php
namespace App\Controllers;
use App\Core\Controller;
class HomeController extends Controller {
    public function index() {
        return $this->view('home', [
            'title' => '欢迎页面',
            'content' => 'Hello, PHP Framework!'
        ]);
    }
    public function about() {
        return $this->json([
            'name' => 'My PHP App',
            'version' => '1.0.0'
        ]);
    }
}

创建视图 (app/Views/home.php)

<!DOCTYPE html>
<html>
<head><?= $title ?></title>
</head>
<body>
    <h1><?= $content ?></h1>
</body>
</html>

路由注册 (public/index.php 添加)

// 注册路由
$router->get('/', 'HomeController@index');
$router->get('/about', 'HomeController@about');
$router->get('/user', 'UserController@show');
$router->post('/user/store', 'UserController@store');

Composer 配置 (composer.json)

{
    "name": "myapp/php-framework",
    "require": {
        "php": ">=7.4",
        "vlucas/phpdotenv": "^5.4"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "scripts": {
        "start": "php -S localhost:8000 -t public"
    }
}

使用 composer 安装

# 初始化项目
composer init
# 安装依赖
composer install
# 使用内置服务器运行
php -S localhost:8000 -t public

完整框架功能完善

模型基类 (app/Core/Model.php)

<?php
namespace App\Core;
class Model {
    protected $db;
    public function __construct() {
        $this->db = Database::getInstance();
    }
    public function all() {
        $table = $this->getTableName();
        return $this->db->fetchAll("SELECT * FROM {$table}");
    }
    public function find($id) {
        $table = $this->getTableName();
        return $this->db->fetch(
            "SELECT * FROM {$table} WHERE id = ?", [$id]
        );
    }
    protected function getTableName() {
        $class = get_called_class();
        return strtolower(basename(str_replace('\\', '/', $class)));
    }
}

中间件类 (app/Core/Middleware.php)

<?php
namespace App\Core;
abstract class Middleware {
    abstract public function handle($request, $next);
}

全局助手函数 (app/Helpers/functions.php)

<?php
if (!function_exists('base_path')) {
    function base_path($path = '') {
        return BASE_PATH . ($path ? '/' . $path : '');
    }
}
if (!function_exists('env')) {
    function env($key, $default = null) {
        return $_ENV[$key] ?? $default;
    }
}
if (!function_exists('dd')) {
    function dd(...$vars) {
        foreach ($vars as $var) {
            var_dump($var);
        }
        die();
    }
}

最佳实践建议

  1. 错误处理:使用 try-catch 处理异常,避免直接暴露错误信息
  2. 安全性:使用 PDO 参数化查询防止 SQL 注入
  3. 日志记录:使用 Monolog 等日志库记录系统日志
  4. 缓存机制:实现简单的文件或 Redis 缓存
  5. CSRF保护:添加表单令牌验证
  6. 输入验证:对所有用户输入进行验证和过滤

这个基础框架可以作为您开发项目的起点,您可以根据实际需求添加更多功能,如模板引擎、ORM、验证器等,建议参考成熟的PHP框架(如Laravel、Symfony)的设计理念来不断完善您的框架。

抱歉,评论功能暂时关闭!