如果您查看生成的代理类之一,您会发现__load()
和__clone()
函数都抛出EntityNotFoundException
.
__load()
当您“懒惰地”调用该函数时,将调用该函数getName()
。
class ObjectB extends \Foo\Entity\ObjectB implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
...
public function getName()
{
$this->__load();
return parent::getName();
}
...
}
你基本上有几个选择,第一个是使用try/catch
块。
try {
$name = $objectB->getName();
} catch (\Doctrine\ORM\EntityNotFoundException $e) {
$name = null;
}
或者你可以看看实现这个__wakeup()
函数ObjectB
并可能自己处理这个(尽管你很可能需要抛出一个异常)。
最后,如果您有野心,您可以更改Proxy
模板。\Doctrine\ORM\Proxy\ProxyFactory
包含模板。
/** Proxy class code template */
private static $_proxyClassTemplate =
'<?php
namespace <namespace>;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
*/
class <proxyClassName> extends \<className> implements \Doctrine\ORM\Proxy\Proxy
{
private $_entityPersister;
private $_identifier;
public $__isInitialized__ = false;
public function __construct($entityPersister, $identifier)
{
$this->_entityPersister = $entityPersister;
$this->_identifier = $identifier;
}
/** @private */
public function __load()
{
if (!$this->__isInitialized__ && $this->_entityPersister) {
$this->__isInitialized__ = true;
if (method_exists($this, "__wakeup")) {
// call this after __isInitialized__to avoid infinite recursion
// but before loading to emulate what ClassMetadata::newInstance()
// provides.
$this->__wakeup();
}
if ($this->_entityPersister->load($this->_identifier, $this) === null) {
throw new \Doctrine\ORM\EntityNotFoundException();
}
unset($this->_entityPersister, $this->_identifier);
}
}
您应该能够摆脱EntityNotFoundException
在__load()
and__clone()
函数中的抛出,尽管可能会有意想不到的副作用。如果您计划定期升级 Doctrine,您可能还希望将此更改视为一个补丁。