莫方教程网

专业程序员编程教程与实战案例分享

php实现一个基本的 MVC 框架

以下是一个简单的 PHP 框架的代码示例:

<?php

// 定义应用根目录
define('APP_ROOT', dirname(__FILE__));

// 自动加载类文件
spl_autoload_register(function($class) {
    require_once APP_ROOT . '/classes/' . $class . '.php';
});

// 路由分发
$uri = $_SERVER['REQUEST_URI'];
$route = Route::dispatch($uri);

// 控制器调用
$controller_name = $route['controller'] . 'Controller';
$controller = new $controller_name();
$action = $route['action'] . 'Action';
$controller->$action();

// 路由类
class Route {
    public static function dispatch($uri) {
        $parts = explode('/', $uri);
        $controller = !empty($parts[1]) ? $parts[1] : 'index';
        $action = !empty($parts[2]) ? $parts[2] : 'index';
        return array(
            'controller' => $controller,
            'action' => $action
        );
    }
}

// 控制器基类
abstract class Controller {
    protected function render($view, $params = array()) {
        extract($params);
        require_once APP_ROOT . '/views/' . $view . '.php';
    }
}

// 首页控制器
class IndexController extends Controller {
    public function indexAction() {
        $this->render('index/index', array(
            'message' => 'Hello, world!'
        ));
    }
}

该示例实现了一个基本的 MVC 框架,可以根据 URL 路径调用不同的控制器和动作,并自动加载类文件。当然,这仅仅是一个非常简单的框架,实际开发中可以根据需求进行扩展。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言

    滇ICP备2024046894号-1