如何在前端控制器模式中实现控制反转?

时间:2018-11-20 01:24:08

标签: php dependency-injection

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

所有请求都从位于那里的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()]);
 }

在控制器内部,我将实例化一个Service对象,并在该服务上调用一个方法以检索数据库结果。

该服务又需要一个数据库对象才能与数据库进行交互,我的数据库类类似于我想的单例:

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

0 个答案:

没有答案
相关问题