【发布时间】:2011-04-18 01:11:19
【问题描述】:
我有一个简单的 ORM 实现,由加载和持久化实体的数据映射器组成。每个映射器在内部为从数据库读取的所有实体管理一个身份映射,因此同一实体只加载到内存中一次。
我目前正在使用代理类为相关实体实现延迟加载,该代理类仅在访问实体上的属性时才加载相关数据。我的问题是代理类不是实体本身,并且仅在间接加载实体(通过关系)时使用。因此,任何 === 检查将实际实体与加载相同实体的代理进行比较都将返回 false。我的目标是让实体和客户端代码都不知道代理对象。
代理类看起来像:
class EntityProxy
{
protected $_entity;
protected $_loader;
public function __construct(EntityProxyLoader $loader)
{
$this->_loader = $loader;
}
protected function _load()
{
if (null === $this->_entity)
{
$this->_entity = $this->_loader->load();
unset($this->_loader);
}
}
public function __get($name)
{
$this->_load();
return $this->_entity->$name;
}
public function __set($name, $value)
{
$this->_load();
$this->_entity->$name = $value;
}
}
映射器看起来像:
class PersonEntityMapper
{
// Find by primary key
public function find($id)
{
if ($this->inIdentityMap($id)
{
return $this->loadFromIdentityMap($id);
}
$data = ...; // gets the data
$person = new Person($data);
// Proxy placeholder for a related entity. Assume the loader is
// supplied the information it needs in order to load the related
// entity.
$person->Address = new EntityProxy(new EntityProxyLoader(...));
$this->addToIdentityMap($id, $person);
return $person;
}
}
class AddressEntityMapper
{
// Find by primary key
public function find($id)
{
...
$address = new AddressEntity($data);
$address->Person = new EntityProxy(new EntityProxyLoader(...));
$this->addToIdentityMap($id, $address);
return $address;
}
}
如果我加载具有相关“AddressEntity”的“PersonEntity”记录,然后通过“AddressEntityMapper”直接加载相同的“AddressEntity”记录并比较两个对象,它们将不一样(因为一个是委托的代理)。有没有办法覆盖 PHP 的内置对象比较?关于在不将代理感知代码引入实体和/或客户端代码的情况下更好地处理此问题的任何建议?
另外,我知道采用现有和已建立的 ORM 对我有利,但有各种问题阻止我这样做。
【问题讨论】:
标签: php orm lazy-loading identity