
页面控制器设计模式是基于 web 的系统中使用的常见架构方法。它通过专用特定控制器来处理单个页面或请求的逻辑来组织控制流。这种方法有助于隔离职责,使代码库更易于维护和发展。
在页面控制器模式中,每个页面(或一组具有类似行为的页面)都有自己的控制器,负责:
典型的实现涉及以下组件:
流动
立即学习“PHP免费学习笔记(深入)”;
文件结构
/htdocs
/src
/controllers
homecontroller.php
aboutcontroller.php
/services
viewrenderer.php
/views
home.html.php
about.html.php
/public
index.php
/routes.php
composer.json
自动加载器
{
"autoload": {
"psr-4": {
"app\": "htdocs/"
}
}
}
composer dump-autoload
模板
主页和about.html.php.
的模板
<!doctype html>
<html>
<head>
<title><?= htmlspecialchars($title) ?></title>
</head>
<body>
<h1><?= htmlspecialchars($title) ?></h1>
<p><?= htmlspecialchars($content) ?></p>
</body>
</html>
viewrenderer
namespace appservices;
class viewrenderer {
public function render(string $view, array $data = []): void {
extract($data); // turns array keys into variables
include __dir__ . "/../../views/{$view}.html.php";
}
}
homecontroller
处理主页逻辑。
namespace appcontrollers;
use appservicesiewrenderer;
class homecontroller {
public function __construct(private viewrenderer $viewrenderer)
{
}
public function handlerequest(): void {
$data = [
'title' => 'welcome to the site',
'content' => 'homepage content.',
];
$this->viewrenderer->render('home', $data);
}
}
关于控制器
处理“关于我们”页面逻辑。
namespace appcontrollers;
use appservicesiewrenderer;
class aboutcontroller
{
public function __construct(private viewrenderer $viewrenderer)
{
}
public function handlerequest(): void {
$data = [
'title' => 'about us',
'content' => 'information about the company.',
];
$this->viewrenderer->render('about', $data);
}
}
routes.php
定义到控制器的路由映射。
use appcontrollershomecontroller;
use appcontrollersboutcontroller;
// define the routes in an associative array
return [
'/' => homecontroller::class,
'/about' => aboutcontroller::class,
];
index.php
应用程序的入口点。
require_once __DIR__ . '/../vendor/autoload.php';
use AppServicesViewRenderer;
// Include the routes
$routes = require_once __DIR__ . '/../routes.php';
// Instantiate the view rendering service
$viewRenderer = new ViewRenderer();
// Get the current route from the request URI
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Check if the route exists and resolve the controller
if (isset($routes[$requestUri])) {
$controllerClass = $routes[$requestUri];
$controller = new $controllerClass($viewRenderer);
$controller->handleRequest();
} else {
http_response_code(404);
echo "Page not found.";
}
优点
缺点
对于更复杂的项目,存在大量逻辑重用或多个入口点,前端控制器或完整mvc架构等模式可能更合适。
以上就是PHP 设计模式:页面控制器的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号