【问题标题】:Should Application logic have access to repositories?应用程序逻辑是否应该有权访问存储库?
【发布时间】:2020-02-24 04:55:19
【问题描述】:

考虑到 DDD 方法,我将一个类移动到一个公共文件夹,因为它将在模块之间共享。问题是我不知道如何使它与依赖注入和容器一起工作。

基本上,MenuService generate 方法,创建一个自动生成器的实例,从 MenuRepository 传递 4 个数组;

MenuService.php

namespace MP\Application\Services;

use MP\Domain\Repositories\Repository;
use MP\Application\Generation\AutoGenerator;

class MenuService {

    private $repository;   

    public function __construct(Repository $repository){
        $this->repository = $repository;
    }

    public function generate(){
        // fetch/set $recipes, $menu, $settings;
        $generate = new AutoGenerator($recipesArr, $menuArr, $allIngredients);
    }
}

在这里传递$allIngredients 的唯一原因是因为AutoGenerator 实例化了另一个名为Scaler 的类,主方法称为scale($recipe, $percentage, $AllIngredients),这是在自动生成器类中唯一使用$allIngredients 的地方。

class AutoGenerator {
    public function add(...){
        $percentage = new Percentage(...); 
        $scaler = new Scaler();
        $try = $scaler->scale($recipe, $percentage, $this->allIngredients);

        if($try->isSuccess()){
            ...
        }
    }
}

我正在尝试使用 MenuService 删除所有对 AutoGenerator 的依赖,最后是 Scaler...基本上,我使用 __invoke 方法创建了名为 Ingredients 的类,该方法在构造函数中获取存储库,它在早期实例化软件,现在我将它注入到构造函数中。

问题是 AutoGenerator 现在无法实例化 Scaler 类,因为它具有构造函数依赖项,这意味着 AutoGenerator 类现在必须将 Scaler 作为依赖项传递......这导致了我的以下问题......在哪里我应该通过 $recipesArr 和 $menuArr 吗?

我问的原因是因为我不确定我是否必须创建一个类来返回一个数据库查询,这样我才能在构造函数中传递它。 $recipesArr/$allIngredients 来自RecipeRepository,$menuArr 来自MenuRepository;

或者我应该只在缩放器构造函数中注入 RecipeRepository 和 MenuRepository 吗?

这是文件夹结构:

MP\Application\Generation\Common\Scaler;
MP\Application\Generation\AutoGenerator;

SHARED\Domain\Repositories\Ingredients;

MP\Domain\Repositories\RecipeRepository;
MP\Domain\Repositories\MenuRepository;

【问题讨论】:

  • 在您的问题中,您描述了solution 并询问它有什么问题。相反,我会描述the problem - 域,以及您想要实现的目标。然后有人可能会对模型是否好有意见。

标签: php domain-driven-design


【解决方案1】:

答案是:是的

应用程序服务应该关心读取和持久化。正确的用法是这样的:

  1. 根据一些输入 (ID),您需要获取给定的域实体
  2. 然后通过其他输入参数调用实体上的方法/属性,或者使用域服务传入域实体和新输入。
  3. 域服务(或对实体的调用)将对域实体进行更改。这些变化仍在记忆中。
  4. 所以最后您需要保留这些更改。

我刚刚在 Google 上搜索了一下,更多详情请查看:https://blog.arkency.com/application-service-ruby-rails-ddd/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2010-10-10
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多