gpt4 book ai didi

php - 存储库模式和共享实体

转载 作者:搜寻专家 更新时间:2023-10-31 20:39:08 25 4
gpt4 key购买 nike

我正在考虑使用存储库设计模式进行数据抽象,我正在使用 Phalcon PHP 框架并使用以下结构:

ModelA
|- Entity
|- Entity1.php
|- Entity2.php
|- Entity3.php
|- Repository
|- RepositoryA.php
|- Service
|- ServiceA.php

现在,如果我必须在另一个 ModelB 中使用相同的 Entity2.php,我将失去存储库模式最方便的用途,即我只能通过修改 RepositoryA 来更改 Entity2.php 的数据源。 php,而不是担心谁也可能使用该实体。如果我不允许直接访问实体,我就无法执行跨多个存储库的连接。

处理此问题的最佳方法是什么?

最佳答案

根据您的描述,我假设 ModelA/Repository/RepositoryA.php 是一个具体的实现。如果我正确理解你的问题,你还想拥有 ModelB/Repository/RepositorA.php,它们都访问相同的数据库表以提供相同的实体(比如 ModelA/Entity/EntityA.php)。

您可以做的一件事是将这两个 RepositoryA 类都转换为接口(interface),然后您可以使用一个具体类在别处实现这些接口(interface),如下所示:

ModelA
|- Entity
|- Entity1.php
|- Entity2.php
|- Entity3.php
|- Repository
|- RepositoryA.php (interface, for dealing with ModelA\Entity\Entity1)
|- Service
|- ServiceA.php (depends on ModelA\Repository\RepositoryA)
ModelB
|- Repository
|- RepositoryB.php (interface, for dealing with ModelA\Entity\Entity1)
|- Service
|- ServiceB.php (depends on ModelB\Repository\RepositoryB)
Infrastructure
|- Repository
|- ConcreteEntity1Repository (concrete class that implements both RepositoryA and RepositoryB interfaces. Somehow, an instance of this is passed to both ServiceA and ServiceB (dependancy injection or whatever you like))

这样,您就可以将正在使用的具体实现与服务层分开,让您在需要时更灵活地进行更改。 (作为一个额外的好处,这将使执行诸如对代码进行单元测试之类的事情变得更加容易。)

通过这种方法,您可以有效地在两个模型中使用相同的存储库,但不会在它们之间创建任何耦合。根据您的系统架构,以这种方式进行设置可能会相当复杂,而且对于这种情况来说可能有点过分了。

另一种方法可能是不让 RepositoryA 和 RepositoryB 成为接口(interface),而是将它们变成委托(delegate)其工作的具体类,方法是将一个公共(public)的“Entity1Repository”传递给它们(并让 RepositoryA 和 RepositoryB 包装它们需要的调用) ,或者通过创建一个它们都扩展的抽象基类,其中包含任何通用功能。

这还有一个额外的好处,即您还可以添加特定于一个模型的东西,而无需它成为另一个模型的一部分。 (例如,ModelA\Repository\RepositoryA 可以有一个函数 findRelatedTo(Entity3 $entity3),而不强制 ModelB 知道 Entity3 是什么。)

关于php - 存储库模式和共享实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com