PHP高级编程示例项目

admin23小时前it知识18
<?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开发最佳实践。


标签: 分享IT知识
返回列表

上一篇:camel

下一篇:calf

相关文章

优美程序是怎样的

程序优美是一个主观的概念,每个人可能会有不同的看法。然而,以下是一些可能导致程序优美的因素:简洁性:优美的程序应该尽可能地简洁明了。这意味着应该使用尽可能少的数据结构和算法,以及尽可能简单的代码。可读...

享受工作:找到事业与生活的平衡点

工作是我们日常生活中不可或缺的一部分。我们花费大量的时间和精力在工作中,因此,如何享受工作并找到事业与生活的平衡点就显得尤为重要。在这篇文章中,我们将探讨如何享受工作,让事业和生活愉快并行。首先,了解...

湖边

湖边,一片静谧的美好。清晨的阳光洒在湖面上,波光粼粼,让人心旷神怡。湖上的荷叶轻轻摇曳,荷花争奇斗艳,仿佛在向人们展示着它们的美丽。湖边的柳树依依,芦苇丛生,形成了一道道天然的屏障,让人感到一种隐秘的...

夏天的台风

夏天,是一个充满活力和生命力的季节,但同时也伴随着台风的出现。每年的这个时期,台风如同一股强大的自然力量,给人们的生命和财产带来了一定的威胁。在台风的肆虐中,可以看到大自然的威力与无情。台风带来的强风...

拖延症重度患者怎样自救

对于拖延症的重度患者,自救的关键在于以下几点:识别并克服拖延的借口。拖延常常因为我们害怕、不确定、不想不舒服而找到各种借口。我们必须识破这些借口,并对自己说:“如果我拖延,后果将不堪设想。”制定清晰的...

如何学习 javascript

学习JavaScript需要以下步骤:基础语法:学习JavaScript的基础语法,包括变量、数据类型、函数、循环、条件语句等。DOM 操作:学习如何操作 DOM,例如获取和修改元素、添加和删除事件处...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。