当前位置:首页 > PHP

php 实现mvc

2026-01-14 13:19:12PHP

PHP 实现 MVC 架构的方法

MVC(Model-View-Controller)是一种常见的软件设计模式,用于分离业务逻辑、用户界面和用户输入。以下是 PHP 实现 MVC 架构的关键步骤:

目录结构

典型的 MVC 目录结构如下:

app/
    controllers/
    models/
    views/
public/
    index.php

入口文件

public/index.php 是应用入口,负责初始化路由和调度请求:

require_once '../app/bootstrap.php';
$router = new Router();
$router->dispatch($_SERVER['REQUEST_URI']);

路由类

路由类解析 URL 并调用对应的控制器和方法:

class Router {
    public function dispatch($url) {
        $urlParts = explode('/', trim($url, '/'));
        $controllerName = isset($urlParts[0]) ? ucfirst($urlParts[0]) . 'Controller' : 'HomeController';
        $action = isset($urlParts[1]) ? $urlParts[1] : 'index';

        if (class_exists($controllerName)) {
            $controller = new $controllerName();
            if (method_exists($controller, $action)) {
                $controller->$action();
            } else {
                throw new Exception("Method $action not found");
            }
        } else {
            throw new Exception("Controller $controllerName not found");
        }
    }
}

控制器示例

控制器处理用户请求并协调模型和视图:

class UserController {
    public function index() {
        $userModel = new User();
        $users = $userModel->getAll();
        include '../app/views/user/index.php';
    }
}

模型示例

模型处理数据逻辑和数据库交互:

php 实现mvc

class User {
    private $db;

    public function __construct() {
        $this->db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
    }

    public function getAll() {
        $stmt = $this->db->query('SELECT * FROM users');
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

视图示例

视图负责展示数据:

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <h1>User List</h1>
    <ul>
        <?php foreach ($users as $user): ?>
            <li><?php echo htmlspecialchars($user['name']); ?></li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

自动加载

使用自动加载避免手动包含文件:

spl_autoload_register(function ($className) {
    $file = '../app/' . str_replace('\\', '/', $className) . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

配置管理

创建配置文件管理数据库等设置:

php 实现mvc

return [
    'db' => [
        'host' => 'localhost',
        'name' => 'test',
        'user' => 'username',
        'pass' => 'password'
    ]
];

高级实现建议

依赖注入

使用依赖注入容器管理对象创建:

class Container {
    private $instances = [];

    public function get($key) {
        if (!isset($this->instances[$key])) {
            $this->instances[$key] = new $key();
        }
        return $this->instances[$key];
    }
}

前端控制器

使用单一入口点处理所有请求:

$request = $_SERVER['REQUEST_URI'];
$router->dispatch($request);

模板引擎

集成 Twig 或 Blade 等模板引擎:

$loader = new \Twig\Loader\FilesystemLoader('../app/views');
$twig = new \Twig\Environment($loader);
echo $twig->render('index.twig', ['users' => $users]);

ORM 集成

使用 Eloquent 或 Doctrine 替代原生 SQL:

class User extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'users';
}

这种实现方式提供了清晰的关注点分离,使代码更易于维护和扩展。可以根据项目需求调整复杂度,从简单实现逐步过渡到使用框架级别的解决方案。

标签: phpmvc
分享给朋友:

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用LIMIT和OFFSET进行数据库查询分页。通过计算当前页码和每页显示数量,动态生成SQL语句。 $page = isset($_GET['page']) ? (int…

php记住密码怎么实现

php记住密码怎么实现

使用Cookie实现记住密码功能 在PHP中,可以通过设置Cookie来记住用户的登录状态。以下是一个简单的实现方式: // 用户登录验证成功后 if ($login_success) {…

php如何实现直播

php如何实现直播

实现直播功能的方法 PHP可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTMP协…

php 实现登录

php 实现登录

PHP 登录功能实现 使用 PHP 实现登录功能通常需要结合数据库验证和会话管理。以下是一个基本的登录实现流程: 数据库准备 创建用户表存储用户名和密码(建议使用哈希加密): CREATE TAB…

php实现接口

php实现接口

PHP 实现接口的方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不实现具体功能。类可以实现一个或多个接口,并必须实现接口中定义的所有方法。 定义接口 接口使用 inter…

php 实现秒杀

php 实现秒杀

PHP 实现秒杀的关键技术 秒杀系统需要解决高并发、超卖、性能瓶颈等问题。以下是实现秒杀的核心方案: 使用 Redis 预减库存 将商品库存提前加载到 Redis 中,通过原子操作保证库存准确性:…