我在我的 DataMappers 中实现了一个小 IdentityMap,它可以正常工作,因为它知道是否已经加载了一个对象,但它没有正确分配内存中的对象。
我已经尽可能地将代码简化(无论如何并不复杂)到一个实体,没有数据库等。有人可以解释为什么在lookup()方法中没有正确地将已经加载的客户对象分配给传入的客户目的?
客户.php
class Customer {
private $id;
private $name;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
客户映射器
class CustomerMapper {
private $identityMap;
public function __construct(IdentityMap $identityMap) {
$this->identityMap = $identityMap;
}
public function fetch(Customer $customer) {
if( $this->identityMap->lookup($customer) ) {
return true;
}
$this->assign($customer, array('id' => 1, 'name' => 'John'));
}
private function assign(Customer $customer, Array $row) {
$customer->setId($row['id']);
$customer->setName($row['name']);
$this->identityMap->add($customer);
}
}
身份映射
class IdentityMap {
private $customers;
public function lookup(Customer $customer) {
if( !array_key_exists($customer->getId(), $this->customers) ) {
return false;
}
$customer = $this->customers[$customer->getId()]; //Something wrong here?
return true;
}
public function add(Customer $customer) {
$this->customers[$customer->getId()] = $customer;
}
}
当我然后运行这个:
$identityMap = new IdentityMap();
$customerMapper = new CustomerMapper($identityMap);
for( $i = 0; $i < 3; $i++ ){
$customer = new Customer();
$customer->setId(1);
$customerMapper->fetch($customer);
echo 'ID: ' . $customer->getId() . '<br>Name: ' . $customer->getName() . '<br><br>';
}
输出:
ID: 1
Name: John
ID: 1
Name:
ID: 1
Name:
为什么第二个和第三个 Customer 对象没有名称?我相当确定 lookup() 方法的分配部分存在问题。自昨晚以来,我一直在尝试和阅读所有内容。
我已将lookup() 方法签名更改为在传入的对象前面有“&”符号,但没有运气。