【问题标题】:OOP Pattern with methods calling Repositories带有调用存储库的方法的 OOP 模式
【发布时间】:2014-11-27 17:42:39
【问题描述】:

我有一个 DashboardService 类(在 symfony2 中定义为服务),我用它调用一些方法从一些存储库中获取结果(只是查询)并显示数据。

class DashboardService {

/**
 * @var EntityManager 
 */
private $em;

public function __construct(EntityManager $em) {
    $this->em = $em;
}

public function getTotalActiveCampaignsByMonth($month) {

    $campaigns = $this->em->getRepository("WMAdminBundle:Campaign")->countAllActiveCampaignsByMonth($month);

    return $campaigns;
}

public function getTotalContactsByMonth($month) {

    $contacts = $this->em->getRepository("WMAdminBundle:Contact")->countAllContactsSentByMonth($month);

    return $contacts;
}

public function getTotalCAByMonth($month) {
    $ca = $this->em->getRepository("WMAdminBundle:ContactCampaign")->getAllCAByMonth($month);

    return $ca;
}

public function getTop10RentabilityCampaigns() {
    $campaigns = $this->em->getRepository("WMAdminBundle:Campaign")->findAllTop10Rentability();

    return $campaigns;
}

public function getTop10ContactCampaigns() {
    $campaigns = $this->em->getRepository("WMAdminBundle:Campaign")->findAllTop10Contacts();

    return $campaigns;
}

}

这个类是 OOP 模式还是什么?

【问题讨论】:

    标签: php oop symfony doctrine repository-pattern


    【解决方案1】:

    它就像典型分层架构中的基本应用程序服务。

    应用程序服务:被外部消费者用来与您的系统对话(想想 Web 服务)。如果消费者需要访问 CRUD 操作,他们将在这里公开。

    【讨论】:

    • 好的,所以你认为在我的控制器中使用这个类是一个好习惯:$this->get("dashboard")-> getTotalActiveCampaignsByMonth($month); 或者最好直接在控制器中做:$this->em->getRepository("WMAdminBundle:Campaign")->countAllActiveCampaignsByMonth($month); 并删除我的服务类?
    • 在控制器中注入(或定位)存储库并使用它们不是一个好主意。因为并非所有存储库调用都只是获取数据。在大多数命令调用中,您需要验证和检查一些业务规则,然后调用存储库方法。这就是您应该在应用程序服务中做的事情。
    • 好的,但在我的情况下,我的 Campaign Service 中没有业务逻辑,只调用存储库进行查询。
    • 在这种情况下,您可以在控制器中调用您的存储库,但我不建议这样做。因为控制器是“接口”层的一部分,应该只调用服务。将您的存储库紧密耦合到您的控制器可能会导致您将来进行大量更改。 (考虑在不同控制器中使用的查询,现在您想将其更改为调用两个存储库方法。您应该在所有控制器中更改它)。即使在 CQRS 模式中,总有一个外观服务可以抽象查询模型:CQRS pattern diagram
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2015-10-04
    • 2021-11-02
    • 2020-11-03
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多