Doctrine 2: Can entities be saved into sessions?

前端 未结 2 863
梦毁少年i
梦毁少年i 2020-12-14 04:43

I\'m having a problem with lazy loading after I save an entity into a PHP session. Is there any workaround for this?

2条回答
  •  生来不讨喜
    2020-12-14 05:21

    The accepted answer quotes accurately the Doctrine documentation.

    However, there are few more pages on the subject explaining how to serialize entities and store them the session. Entities in the Session says that the entities must be detached before storing in the session and then merged when restoring from the session.

    On this page there are sections about detaching and merging entities.

    Saving:

    $em = GetEntityManager();
    $user = $em->find("User", 1);
    $em->detach($user);
    $_SESSION['user'] = $user;
    

    Restoring:

    $em = GetEntityManager();
    session_start();
    if (isset($_SESSION['user']) && $_SESSION['user'] instanceof User) {
        $user = $_SESSION['user'];
        $user = $em->merge($user);
    }
    

提交回复
热议问题