php单一入口实现
单一入口实现原理
PHP单一入口模式通过一个中心文件(如index.php)处理所有请求,根据参数或URL路由分发到不同控制器。这种设计便于统一管理权限、日志和全局配置。
基本实现步骤
创建入口文件index.php,通常放置在项目根目录:
<?php
// 定义应用路径常量
define('APP_PATH', dirname(__FILE__));
// 加载配置文件
require APP_PATH . '/config.php';
// URL路由解析
$route = isset($_GET['r']) ? $_GET['r'] : 'site/index';
list($controller, $action) = explode('/', $route);
// 控制器类文件引入
$controllerClass = ucfirst($controller) . 'Controller';
require APP_PATH . '/controllers/' . $controllerClass . '.php';
// 实例化并执行
$controllerInstance = new $controllerClass();
$controllerInstance->$action();
URL重写配置
Apache服务器需配置.htaccess文件实现美观URL:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?r=$1 [L,QSA]
Nginx服务器配置示例:
location / {
try_files $uri $uri/ /index.php?$args;
}
路由优化方案
采用更灵活的路由解析方案:
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($uri, '/'));
$controller = $segments[0] ?? 'home';
$action = $segments[1] ?? 'index';
$params = array_slice($segments, 2);
自动加载实现
使用spl_autoload_register实现类自动加载:
spl_autoload_register(function ($className) {
$file = APP_PATH . '/lib/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require $file;
}
});
异常处理机制
统一错误处理可增强稳定性:
set_exception_handler(function ($exception) {
header('Content-Type: application/json');
echo json_encode([
'error' => $exception->getMessage(),
'code' => $exception->getCode()
]);
});
性能优化建议
引入OPcache加速:
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=4000
缓存路由解析结果可减少重复计算,使用文件缓存或内存缓存存储常用路由映射关系。







