gpt4 book ai didi

php - 依赖注入(inject)和工作单元模式

转载 作者:可可西里 更新时间:2023-10-31 23:44:15 25 4
gpt4 key购买 nike

我有一个难题。我使用 DI(阅读:工厂)为自制 ORM 提供核心组件。容器根据请求提供数据库连接、DAO、映射器及其生成的域对象。

这是映射器和域对象类的基本概述

class Mapper{
public function __constructor($DAO){
$this->DAO = $DAO;
}

public function load($id){
if(isset(Monitor::members[$id]){
return Monitor::members[$id];

$values = $this->DAO->selectStmt($id);
//field mapping process omitted for brevity
$Object = new Object($values);
return $Object;
}
}

class User(){
public function setName($string){
$this->name = $string;
//mark modified by means fair or foul
}
}

ORM 还包含一个基于工作单元模式的类(监视器),即

class Monitor(){
private static array modified;
private static array dirty;
public function markClean($class);
public function markModified($class);
}

ORM 类本身只是协调从 DI 容器中提取的资源。因此,要实例化一个新的用户对象:

$Container = new DI_Container;
$ORM = new ORM($Container);
$User = $ORM->load('user',1);
//at this point the container instantiates a mapper class
//and passes a database connection to it via the constructor
//the mapper then takes the second argument and loads the user with that id
$User->setName('Rumpelstiltskin');//at this point, User must mark itself as "modified"

我的问题是这样的。当用户在域对象类上设置值时,我需要在 Monitor 类中将该类标记为“脏”。我可以看到三个选项之一

1: 将 Monitor 类的实例传递给域对象。我注意到这在 FirePHP 中被标记为递归 - 即 $this->Monitor->markModified($this)

2:直接在域对象中实例化监视器——这会破坏 DI 吗?3:将 Monitor 方法设为静态,并从域对象内部调用它们 - 这也会破坏 DI,不是吗?

你推荐的行动方案是什么(除了使用现有的 ORM,我这样做是为了好玩......)

最佳答案

好的,我明白了。这个怎么样:

 $user = new User;
$monitoredUser = new Monitor( $user );

//at update in class Monitor:
Monitor::markDirty( $this );

现在您使用 Monitor 作为装饰器;它在用户对象或处理传入请求的任何其他对象周围添加了一个外壳。如果一个对象被更新,它将被监视器标记为脏,但是因为监视器为此使用静态方法,它保留在当前类范围内,从而避免递归。

关于php - 依赖注入(inject)和工作单元模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3012657/

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