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开发最佳实践。


标签:

相关文章

前端面向对象

在前端开发中,“面向对象”思想的应用主要集中在代码组织、组件设计和架构模式等方面。以下是前端面向对象开发的核心概念和实践:‌1. 面向对象的核心概念‌‌封装‌:将数据(属性)和操作数据的方法(行为)捆...

前端的奥妙

精妙之处可概括为以下维度:🎨 ‌一、隐形魔法:重塑人机交互的温度‌‌无感适配的艺术‌响应式设计让图文排版随设备屏幕自动流淌,滑动如丝绸般顺滑,技术如空气般自然融入生活,成为用户无感却不可或缺的体验基石...

前端技术演进的故事

前端技术的发展历程充满了技术突破与开发者智慧的闪光点,以下是几个关键阶段的演进故事:一、洪荒时代(1990-1994)万维网之父蒂姆·伯纳斯-李在CERN工作时,为解决研究人员信息共享问题,发明了首个...

前端高级函数方法

前端高级函数方法是JavaScript编程中的核心概念,主要包括高阶函数、函数式编程工具以及各种实用封装方法高阶函数与函数式编程高阶函数是指接收函数作为参数或返回函数的函数常见的数组高阶函数包括map...

PHP的主要应用行业及场景

PHP作为一种广泛应用的服务器端脚本语言,主要服务于Web开发领域,并在多个行业中发挥着关键作用。以下是PHP的主要应用行业及场景:1. ‌Web开发与动态网站‌PHP是构建动态网站的核心语言,尤其适...

PHP 优化

一、核心优化方向‌代码层面优化‌‌减少冗余计算‌:避免循环内重复计算,如提前计算不变值($count = count($array))。‌善用内置函数‌:优先使用PHP内置函数(如array_uniq...