pronngo
pronngo

Reputation: 840

Doctrine2 - the entity loaded for session doesn't work

I use Doctrine2 in my ZendFramework project and I've got a not easy to resolve for me a problem...

So, when user has successfully log in to the page, I put his object into the session:

Zend_Auth::getInstance()->getStorage()->write($user);

Everything works fine, but when I refresh the page and load an user from session:

$user = Zend_Auth::getInstance()->getStorage()->read();

And with this $user I can't do any Doctrine2 operations :-/. I'm able to use for example "getId()" method, but when I try for example use $user in any relations:

$session = new App_Model_LogSessions();
$session->setUser($user);
...

I see the Doctrine2 exception:

Entity App_Model_Users is not managed. An entity is managed if its fetched from the database or registered as new through EntityManager#persist

How can I fix this? Is there any method to "reload" the entity? I need to use the session, I don't want to load user from database in every page request. I'd like to load him once and put him to the session.

Thanks!

Upvotes: 0

Views: 1180

Answers (2)

Antoine Hedgecock
Antoine Hedgecock

Reputation: 313

I would recommend that you only store the actual ID and use a cache. But to solve your issue you can always reattach the Entity.

This is how you would do it (I don't recommend doing it but anyway :-P)

// Assume that $em is a instance of the EntityManager
$attachedObject = $em->merge($object);

Upvotes: 0

Gediminas
Gediminas

Reputation: 864

Saving Doctrine entities in sessions (basically what you need) is answered here: Doctrine 2: Can entities be saved into sessions?

Depends on how you are going to use that entity, converting to an array might to the job while it's very simple at the same time. You won't be able to use it as an entity (persist and etc) but you will be able to access the data.

Upvotes: 1

Related Questions