php - 如何在前端控制器模式中实现控制反转?
问题描述
我被困在控制器-服务、服务-数据库之间进行依赖注入,我觉得它一团糟。
所有请求都从 public_html 重定向到 index.php,在那里
在 public_html 的 index.php 中,我正在创建一个应用程序对象,为它提供一个路由器并设置一些路由,例如:
$app = new Application(new Router());
$app->addRoute('/questions', (Object)[
'controller' => 'QuestionsController',
'action' => 'getAllQuestions'
]);
我将 URI 与正则表达式路由进行匹配,并根据 Application.php 中映射到控制器和操作的路由以某种方式“动态地”实例化控制器:
if(class_exists($this->controllerNamespace)){
$this->router->setController(new $this->controllerNamespace);
call_user_func_array([$this->router->getController(), $this->router->getAction()], [$this->router->getParams()]);
}
在控制器内部,我将实例化一个服务对象并调用服务上的一个方法来检索数据库结果。
该服务反过来需要一个数据库对象才能与数据库交互,而我的数据库类类似于我想的单例:
static function getInstance():Database
{
if (NULL == self::$database) {
self::$database = new Database();
}
return self::$database;
}
所以我不知道控制器需要什么服务,直到我实际上在控制器内部并且在服务类中实例化的数据库似乎是错误的,我该如何改进整个事情?
我的偏好是没有其他库用于依赖注入控制器或其他使其变得容易的东西,我将其写为学习练习以更好地理解它。
app
src
Controllers
Questions
Answers
Core
Controller
Database
Router
Service
View
Services
Questions
Answers
Views
index.php
Application.php
Config.php
tests
vendor
logs
public_html
assets
index.php
.htaccess
解决方案
推荐阅读
- ios - 金属中的纹理使用
- python - 练习 - 帮助调试嵌套列表理解
- python - discord.py - 如何添加踢/禁止原因?
- c++ - 如何使用 WinDBG 检查进程上下文之外的转储,并获得正确的调用堆栈
- python - 在python中的excel中查找和替换单元格
- java - 如何在 Java 中读取 CSV 文件,然后通过 AES 算法加密
- python - 'flask run' 或 'python run' 使用哪个?
- javascript - HTML 文本,为隐藏字段设置相同的值
- java - 从 Java 到 Base64 到 Python 的序列化 BitSet 或布尔数组
- mysql - Mysql优化/性能,如何高效使用limit | 基于位置的选择