当前位置:首页 > PHP

mvc实现 PHP

2026-02-14 09:25:40PHP

MVC 实现 PHP

MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的逻辑、数据和界面。在 PHP 中实现 MVC 可以提高代码的可维护性和可扩展性。

mvc实现 PHP

项目结构

典型的 MVC 项目结构如下:

mvc实现 PHP

project/
├── app/
│   ├── controllers/
│   ├── models/
│   ├── views/
│   └── core/
├── public/
│   └── index.php
└── config/
  • controllers 处理用户请求和业务逻辑
  • models 负责数据操作和业务规则
  • views 负责展示数据
  • core 包含框架核心类如路由、数据库连接等
  • public 是入口文件和静态资源目录
  • config 存放配置文件

核心组件实现

路由系统

路由负责解析 URL 并调用相应的控制器和方法:

// core/Router.php
class Router {
    protected $routes = [];

    public function add($uri, $controller, $method) {
        $this->routes[$uri] = [
            'controller' => $controller,
            'method' => $method
        ];
    }

    public function dispatch($uri) {
        if (array_key_exists($uri, $this->routes)) {
            $controller = $this->routes[$uri]['controller'];
            $method = $this->routes[$uri]['method'];

            $controller = new $controller();
            $controller->$method();
        } else {
            throw new Exception("Route not found");
        }
    }
}

基础控制器

// core/Controller.php
class Controller {
    protected function view($view, $data = []) {
        extract($data);
        require_once "../app/views/$view.php";
    }

    protected function model($model) {
        require_once "../app/models/$model.php";
        return new $model();
    }
}

示例实现

模型示例

// models/User.php
class User {
    private $db;

    public function __construct() {
        $this->db = new Database(); // 假设已实现数据库类
    }

    public function getUsers() {
        $this->db->query("SELECT * FROM users");
        return $this->db->resultSet();
    }
}

控制器示例

// controllers/Users.php
class Users extends Controller {
    public function index() {
        $user = $this->model('User');
        $data = $user->getUsers();
        $this->view('users/index', $data);
    }
}

视图示例

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

入口文件

// public/index.php
require_once '../app/core/Router.php';
require_once '../app/core/Controller.php';

$router = new Router();

// 添加路由
$router->add('/', 'Home', 'index');
$router->add('/users', 'Users', 'index');

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($uri);

数据库连接

// core/Database.php
class Database {
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;

    private $stmt;
    private $dbh;

    public function __construct() {
        $dsn = "mysql:host={$this->host};dbname={$this->dbname}";
        $options = [
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];

        try {
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        } catch (PDOException $e) {
            die($e->getMessage());
        }
    }

    public function query($sql) {
        $this->stmt = $this->dbh->prepare($sql);
    }

    public function bind($param, $value, $type = null) {
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($param, $value, $type);
    }

    public function execute() {
        return $this->stmt->execute();
    }

    public function resultSet() {
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

自动加载

使用 Composer 的自动加载或实现简单的自动加载:

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

配置管理

// config/config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'mvc_app');

这个实现展示了 PHP 中 MVC 模式的基本结构。实际项目中可能需要更复杂的路由系统、中间件支持、依赖注入等高级功能。

标签: mvcPHP
分享给朋友:

相关文章

单例模式的实现PHP

单例模式的实现PHP

单例模式的基本概念 单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。适用于需要全局唯一对象的场景,如数据库连接、日志管理等。 PHP 单例模式的实现步骤 私有化构造函数…

PHP中实现重定向

PHP中实现重定向

PHP重定向的实现方法 在PHP中,重定向是通过发送HTTP头信息来实现的。以下是几种常见的重定向方法: 使用header()函数 header("Location: https://exampl…

域名转短域名PHP实现

域名转短域名PHP实现

短域名服务的基本原理 短域名服务通过将长URL映射到更短的唯一字符串实现跳转。核心步骤包括生成短码、存储原始URL与短码的对应关系、通过短码重定向到原始URL。 生成短码的常见方法 Base62编码…

PHP实现excel

PHP实现excel

PHP 实现 Excel 操作 读取 Excel 文件 使用 PHP 读取 Excel 文件可以通过 PhpSpreadsheet 库实现。安装该库可以通过 Composer: composer r…

mvc实现 PHP

mvc实现 PHP

MVC 模式概述 MVC(Model-View-Controller)是一种设计模式,用于将应用程序的逻辑分离为三个核心组件:模型(Model)处理数据,视图(View)负责展示,控制器(Contro…

PHP实现预约

PHP实现预约

PHP预约系统实现方法 创建预约系统需要处理用户输入、数据存储和验证。以下是一个基本的PHP预约系统实现框架: 数据库表结构 CREATE TABLE appointments ( id…