【问题标题】:Session unserialize not working with the Entity id会话反序列化不适用于实体 ID
【发布时间】:2014-02-27 14:41:36
【问题描述】:

我有一个实现 Serializable 的实体,如下所示:

class Entity implements \Serializable
{
    /**
     * @var integer $id
     */
    protected $id;

    /**
     * @var string $name
     */
    protected $name;

    /**
     * @see \Serializable::serialize()
     */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->name,
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->name
        ) = unserialize($serialized);
    }
}

在代码中的某个时刻,我从数据库中获取其中一个并将其保存在会话中

// $entity is an instance of Entity
$this->getRequest()->getSession()->set('entity', $entity);

然后,如果我立即尝试让实体返回

$entityFromSession = $this->getRequest()->getSession()->get('entity');

实体是不同的类,id 为 null,但 name 属性工作正常:

get_class($entityFromSession); // returns 'Proxies\__CG__\Bundle\Entity\Entity'
$entityFromSession->getId(); // returns null
$entityFromSession->getNome(); // returns the property correctly.

编辑:这是我在执行 \Doctrine\Common\Util\Debug::dump($entity) 时得到的结果:

object(stdClass)[779]
  public '__CLASS__' => string 'Proxies\__CG__\Bundle\Entity\Entity' (length=35)
  public '__IS_PROXY__' => boolean true
  public '__PROXY_INITIALIZED__' => boolean false
  public 'id' => int 44
  public 'name' => string 'Entity Name' (length=11)

什么? id 信息在那里(44 是数据库中对象的 id。这对我来说没有意义。

【问题讨论】:

    标签: session symfony serialization doctrine-orm


    【解决方案1】:

    当您从会话存储中检索对象时,您已分离实体。您需要致电:

    $entityManager->merge($entity);
    

    【讨论】:

    • 太棒了。我知道这将是那么简单的事情。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多