首页 > 解决方案 > 如何在前端控制器模式中实现控制反转?

问题描述

我被困在控制器-服务、服务-数据库之间进行依赖注入,我觉得它一团糟。

所有请求都从 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

标签: phpdependency-injection

解决方案


推荐阅读