我在DataMapper中实现了一个小型IdentityMap,并且它以它知道对象是否已经加载的方式正常工作但它不会正确分配内存对象。将对象传递给方法,将该对象分配给另一个对象,传递给对象仍然是我传入的同一对象
我已经尽可能地简化了代码(它并不复杂)到一个实体,没有数据库等。有人可以解释为什么在lookup()方法没有正确地分配已经加载的Customer对象在Customer对象中传入?
Customer.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;
}
}
CustomerMapper
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);
}
}
IdentityMap
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:
为什么第二个和第三个顾客对象没有名字?我相当确定lookup()方法中的分配部分存在问题。自从昨晚尝试和阅读所有内容以来,我一直都在这里。
我已将lookup()方法签名更改为在传入的对象前面有“&”符号,但没有运气。
我们必须更深入。就像一个观点! – Dropout
试试这个,'公共函数查找(Customer&$ customer)',以便它通过引用而不是按值传递。 –
@MichaelPerrenoud尝试过,没有运气。还有其他建议吗?它应该在理论上工作,但不应该呢?我不知道什么是错的。 – ibanore