soupdiver
soupdiver

Reputation: 3683

Storing Doctrine Object in $_SESSION

Hey, ive got a mysterious problem at the moment... i have a login service on my website. I use Doctrine as ORM. When the user entered the right combination for username and password i try to store the retrieved user object in my session for later purpose.

$user = new models\User;
$user = $em->getRepository('models\User')->findOneBy(array(
           'username' => $this->input->post('username'),
           'password' => hash("sha512", $this->input->post('password'))
           ));

   if($user != NULL) {
        session_start();
        $_SESSION['user'] = $user;
    redirect('user');
    }

thats a part from my login

       /**
         * @ManyToOne(targetEntity="Country")
         * @JoinColumn(name="country_id", referencedColumnName="id")
         */
        private $country;

user has different attributes like country, address etc.

so my problem is: if the field Country is null (in the db) for the user the login works fine... but if the user is assigned to a country (country has just id and name) my system fails. after the redirect the is no $user in $_SESSION There is no php error or something like this.. the variable just goes away

would it maybe better just storing the id in session and load the user on every page load?

Upvotes: 3

Views: 964

Answers (2)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30013

would it maybe better just storing the id in session and load the user on every page load?

Sure. User data may have changed already on next page load, so you obviously need to refresh data from database, not read old data of the user from session.

references:

PHP: Storing 'objects' inside the $_SESSION

Upvotes: 5

ChrisR
ChrisR

Reputation: 14467

Unless you find some way of storing the state of your object with _sleep and _wakeup and serializing it without losing references you cannot put objects in a session.

I'd indeed go with storing the id and re-retrieving it upon the next request.

Upvotes: 0

Related Questions