超薄3服务层与模型依赖注入

时间:2018-02-13 16:27:50

标签: php model-view-controller dependency-injection slim-3

我使用Slim 3框架创建一个应用程序,它基本上包括动态填充一系列下拉选择语句,然后根据选择生成一个计算数据表。

我原本打算坚持使用MVC布局,但是为了分离出数据访问层(每个模型只处理一个数据项),我决定在阅读后{{}将业务逻辑放入服务层。 3}}

它的结构为:

  • index.php - 路由由不同网页的ajax调用的路由和DIC
  • / models - 包含每个下拉列表中使用的每个数据项的类,例如Country.class.php,Product.class.php等......
  • / controllers - 包含2个用于处理下拉列表的InputController.class.php和用于处理计算的CalculateController.class.php。
  • / views - 包含使用php-views
  • 返回响应的php模板
  • / services - 用于处理业务逻辑和返回要通过控制器传递给视图的数据的服务类

在DIC中,我试图避免将容器传递给其他类,但是我已经遇到了我不确定如何正确注入依赖关系的情况。

在我的index.php文件中,我有以下代码:

//DIC
$container = $app->getContainer();

$container['view'] = function ($container) {
    return new \Slim\Views\PhpRenderer('src/views/');
};

$container['InputService'] = function($container){

    //questionable area
    $model1 = $container->get('model1');
    $model2 = $container->get('model2');
    $model3 = $container->get('model3');

    new InputService($model1, $model2, $model3);
}

$container['InputController'] = function($container){
    $service = $container->get('InputService');
    $view = $container->get('view');
    new InputController($InputService, $view);
}

当特定网页加载时,发送初始ajax调用,其请求2或3个下拉视图(因为在某些情况下,前2/3不依赖于其他选择)。因此InputService注入了3个模型。但是,如果我想使用相同的服务类来处理剩余的下拉列表,我该如何注入正确的模型?

到目前为止我已经有了一些想法:

  • 在实例化服务时注入所有模型,但这意味着每次调用时都会创建大量冗余对象。

    $container['InputService'] = function($container){
    //questionable area
    
    $model1 = $container->get('model1');
    $model2 = $container->get('model2');
    $model3 = $container->get('model3');
    $model4 = $container->get('model4');
    $model5 = $container->get('model5');
    $model6 = $container->get('model6');
    $model7 = $container->get('model7');
    $model8 = $container->get('model8');
    $model9 = $container->get('model9);
    
    new InputService( /*an array of the models*/ );
    }
    
  • 为每个后续下拉列表创建一个不同的服务类,虽然这样做让我想知道是否应该删除服务层并将业务逻辑放在模型中。但是,让模型类从数据库中收集数据不是更好,而不是关心它如何被操纵,因为将来不同的业务逻辑区域将使用相同的数据别的?

    controller1> service1> 3个型号

    controller1> service2> 1个型号

    controller1> service3> 1个型号

    controller1> service4> 1个型号 ...

    或者也许:

    controller1> model1> 3其他型号

    controller1> model5

    controller1> model6 ...

  • 将容器传递给控制器​​,并根据需要为每次调用注入依赖关系。

0 个答案:

没有答案