PHP高级编程示例项目

<?phpnamespace App\Controllers;use App\Models\User;use Exception;class UserController {    private $userModel;        public function __construct() {        $this->userModel = new User();    }        // 获取所有用户    public function index() {        try {            $users = $this->userModel->getAllUsers();            return $this->jsonResponse(['status' => 'success', 'data' => $users]);        } catch (Exception $e) {            return $this->jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);        }    }        // 创建新用户    public function create($data) {        try {            // 数据验证            if (!$this->validateUserData($data)) {                return $this->jsonResponse(['status' => 'error', 'message' => 'Invalid user data'], 400);            }                        $userId = $this->userModel->createUser($data);            return $this->jsonResponse(['status' => 'success', 'user_id' => $userId], 201);        } catch (Exception $e) {            return $this->jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);        }    }        // 获取单个用户    public function show($id) {        try {            $user = $this->userModel->getUserById($id);            if (!$user) {                return $this->jsonResponse(['status' => 'error', 'message' => 'User not found'], 404);            }            return $this->jsonResponse(['status' => 'success', 'data' => $user]);        } catch (Exception $e) {            return $this->jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);        }    }        // 更新用户    public function update($id, $data) {        try {            if (!$this->userModel->getUserById($id)) {                return $this->jsonResponse(['status' => 'error', 'message' => 'User not found'], 404);            }                        if (!$this->validateUserData($data)) {                return $this->jsonResponse(['status' => 'error', 'message' => 'Invalid user data'], 400);            }                        $result = $this->userModel->updateUser($id, $data);            return $this->jsonResponse(['status' => 'success', 'message' => 'User updated']);        } catch (Exception $e) {            return $this->jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);        }    }        // 删除用户    public function delete($id) {        try {            if (!$this->userModel->getUserById($id)) {                return $this->jsonResponse(['status' => 'error', 'message' => 'User not found'], 404);            }                        $this->userModel->deleteUser($id);            return $this->jsonResponse(['status' => 'success', 'message' => 'User deleted']);        } catch (Exception $e) {            return $this->jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);        }    }        // 数据验证    private function validateUserData($data) {        return isset($data['name']) && isset($data['email']) && filter_var($data['email'], FILTER_VALIDATE_EMAIL);    }        // JSON响应    private function jsonResponse($data, $statusCode = 200) {        http_response_code($statusCode);        header('Content-Type: application/json');        return json_encode($data);    }}
<?phpnamespace App\Models;use PDO;use Exception;class User {    private $pdo;        public function __construct() {        $host = 'localhost';        $dbname = 'test_db';        $username = 'root';        $password = '';                try {            $this->pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);        } catch (Exception $e) {            throw new Exception("Database connection failed: " . $e->getMessage());        }    }        // 获取所有用户    public function getAllUsers() {        $stmt = $this->pdo->query("SELECT * FROM users");        return $stmt->fetchAll(PDO::FETCH_ASSOC);    }        // 根据ID获取用户    public function getUserById($id) {        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");        $stmt->execute([$id]);        return $stmt->fetch(PDO::FETCH_ASSOC);    }        // 创建用户    public function createUser($data) {        $stmt = $this->pdo->prepare("INSERT INTO users (name, email, created_at) VALUES (?, ?, NOW())");        $stmt->execute([$data['name'], $data['email']]);        return $this->pdo->lastInsertId();    }        // 更新用户    public function updateUser($id, $data) {        $stmt = $this->pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");        return $stmt->execute([$data['name'], $data['email'], $id]);    }        // 删除用户    public function deleteUser($id) {        $stmt = $this->pdo->prepare("DELETE FROM users WHERE id = ?");        return $stmt->execute([$id]);    }}
<?phpnamespace App\Core;use PDO;use PDOException;class Database {    private static $instance = null;    private $pdo;        private function __construct() {        $host = 'localhost';        $dbname = 'test_db';        $username = 'root';        $password = '';        $options = [            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,            PDO::ATTR_EMULATE_PREPARES => false,        ];                try {            $this->pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password, $options);        } catch (PDOException $e) {            throw new PDOException($e->getMessage(), (int)$e->getCode());        }    }        // 获取单例实例    public static function getInstance() {        if (self::$instance === null) {            self::$instance = new self();        }        return self::$instance;    }        // 获取PDO连接    public function getConnection() {        return $this->pdo;    }        // 防止克隆    private function __clone() {}        // 防止反序列化    public function __wakeup() {        throw new Exception("Cannot unserialize singleton");    }}
<?phpnamespace App\Core;class Router {    private $routes = [];        // 添加GET路由    public function get($path, $callback) {        $this->routes['GET'][$path] = $callback;        return $this;    }        // 添加POST路由    public function post($path, $callback) {        $this->routes['POST'][$path] = $callback;        return $this;    }        // 添加PUT路由    public function put($path, $callback) {        $this->routes['PUT'][$path] = $callback;        return $this;    }        // 添加DELETE路由    public function delete($path, $callback) {        $this->routes['DELETE'][$path] = $callback;        return $this;    }        // 解析请求并执行对应路由    public function resolve($requestUri, $requestMethod) {        // 移除查询参数        $path = parse_url($requestUri, PHP_URL_PATH);                // 查找匹配的路由        if (isset($this->routes[$requestMethod][$path])) {            $callback = $this->routes[$requestMethod][$path];                        // 如果是控制器方法            if (is_string($callback)) {                // 分割控制器和方法                list($controller, $method) = explode('@', $callback);                $controller = "App\\Controllers\\" . $controller;                $controllerInstance = new $controller();                return call_user_func([$controllerInstance, $method]);            }                        // 如果是闭包函数            if (is_callable($callback)) {                return call_user_func($callback);            }        }                // 未找到路由        http_response_code(404);        return json_encode(['status' => 'error', 'message' => 'Route not found']);    }}
<?php// 自动加载spl_autoload_register(function ($class) {    $file = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';    if (file_exists($file)) {        require_once $file;    }});use App\Core\Router;use App\Controllers\UserController;// 创建路由实例$router = new Router();// 定义路由$router->get('/', function() {    return json_encode(['message' => 'Welcome to PHP Advanced Programming Example']);});$router->get('/users', 'UserController@index');$router->get('/users/{id}', 'UserController@show');$router->post('/users', 'UserController@create');$router->put('/users/{id}', 'UserController@update');$router->delete('/users/{id}', 'UserController@delete');// 解析请求echo $router->resolve($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
{    "name": "php-advanced-programming-example",    "description": "PHP高级编程示例项目",    "type": "project",    "require": {        "php": ">=7.4"    },    "autoload": {        "psr-4": {            "App\\": "./"        }    }}

这个PHP高级编程示例项目展示了以下核心概念和特性:

面向对象编程‌:使用命名空间、类和对象实现清晰的代码结构

‌设计模式‌:

单例模式(Database类)

MVC架构模式(控制器、模型分离)

‌数据库操作‌:使用PDO进行安全的数据库交互,包含预处理语句防止SQL注入

‌RESTful API设计‌:实现完整的CRUD操作(创建、读取、更新、删除)

‌错误处理‌:使用异常处理机制确保程序稳定性

‌路由系统‌:自定义路由解析器支持HTTP方法和路径匹配

‌自动加载‌:PSR-4标准的自动加载机制

‌JSON响应‌:标准化API响应格式

‌数据验证‌:基本的输入数据验证机制

‌依赖管理‌:Composer配置文件管理项目依赖

项目结构清晰,遵循现代PHP开发最佳实践。


标签:

相关文章

灵感

灵感的由来可能来自于自然环境、文化背景、生活经验、想象力和创新思维,或其他来源自然环境:大自然以其独特的美丽和秩序,持续激发人类的创造力,自然元素如水、火、空气、土壤和生物等,都为艺术家、科学家和作家...

‌Flutter

‌Flutter 是 Google 开源的一款跨平台应用开发框架,使用 Dart 语言编写,允许开发者通过一套代码库构建高性能、高保真的 iOS 和 Android 应用程序,并支持 Web 和桌面平...

在VS Code中配置和使用UniApp开发的完整指南

UniApp是一个基于Vue.js的跨平台应用开发框架,而VS Code是许多开发者首选的轻量级代码编辑器。本文将详细介绍如何在VS Code中配置UniApp开发环境、创建项目、调试以及解决常见问题...

PHP实现服务端渲染(SSR)

以下是PHP实现服务端渲染(SSR)的核心步骤及实践指南,结合最新技术实践整理:🔧 一、基础实现流程‌环境配置‌安装 PHP ≥8.0 + Web服务器(Apache/Nginx)可选框架:Larav...

php介绍

PHP(Hypertext Preprocessor)是一种广泛使用的开源服务器端脚本语言,主要用于Web开发。以下是关于PHP的关键信息:🔵 基础特性‌语言定位‌专为Web设计,可嵌入HTML,支持...

前端错误集合

⚠️ ‌一、核心运行时错误类型‌‌SyntaxError(语法错误)‌‌原因‌:代码不符合 JavaScript 语法规则(如变量命名不合规、括号缺失等)‌案例‌:var1a = 10;(数字开头的变...