PHP高级编程示例项目

admin1个月前 (02-01)it知识90
<?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

相关文章

双因素理论

双因素理论是美国心理学家弗雷德里克·赫兹伯格(Frederick·Herzberg)于20世纪50年代后期提出的,这一理论的研究重点是组织中的人与工作的关系问题。双因素理论包括保健因素和激励因素。保健...

暴风雨

暴风雨来临之前,天空中弥漫着一股压抑的气息。乌云密布,仿佛覆盖着一片灰暗的帷幕,将整个天地都笼罩在一片阴沉的氛围中。狂风大作,吹拂着路上的尘土和枝叶,让人感到一阵阵的凉意。突然,一声炸雷打破了寂静,紧...

甘草露,甘草露,清凉的甘草露

我知道,那是在七月,骄阳似火,百叶窗紧闭的大卧室里一片昏暗。当他慢慢地、静静地咽气时,在那炎热的夏日午后令人窒息的宁静中,忽然街上传来清脆的铃声,一个响亮的声音划破闷人的溽暑,喊道:“清凉的甘草露!太...

首屏加载优化全解析

首屏加载‌是指用户打开网页或应用时,首次呈现在屏幕上的内容加载完成的时间。首屏加载速度直接影响用户体验,是前端性能优化的关键指标。‌一、首屏加载的重要性‌‌用户体验‌:快速的首屏加载能减少用户等待时间...

php 消息队列例子

‌RabbitMQ方案‌安装扩展:需先安装amqp扩展,通过pecl或源码编译安装‌生产者示例:$connection = new AMQPConnection([...

产品经理与程序员的分工与合作关系分析

一、角色定位与能力差异‌核心职责差异‌程序员的核心能力是技术实现,擅长将需求转化为代码,关注技术可行性(如功能能否实现、性能优化等)产品经理则聚焦需求分析与产品规划,需平衡用户价值、商业目标与技术实现...