Reputation: 463
Situation: It seems impossible to store any objects in the CI_Session since, reading them results in the PHP_Incomplete_Object exceptions, as the session is always started, before loading the models. This way, even when autoloading the Type of object, I am never able to read the data from the session.
I also tried using the "Native Session", but there it's exactly the same problem.
Furthermore I tried storing the object serialized, but when unserializing long after having all the models loaded, it still becomes an object with type "__PHP_Incomplete_Class ".
Anyone know a workaround? And please keep "why would you want an object in the session" answers. Seen enough of those ...
Upvotes: 3
Views: 5046
Reputation: 2122
The only solution I have found so far is to have the class together with the controller (instead of separated as a library).
Not very classy but for some reason it works, while a CI library instance wouldn't.
So basically:
class Main extends CI_Controller {
public function index() {
$game = new Game();
echo $game->id;
$this->session->set_userdata('game',$game);
}
public function restore_game() {
$game = $this->session->userdata('game');
echo $game->id;
}
}
class Game {
public $id;
public function __construct() {
$this->id = rand(0,100);
}
}
Or you could still keep the class in the 'libraries' folder but load it with a classic require_once instead of $this->load->library('Game') which is the kind of object that the session can't handle.
require_once(APPPATH . 'libraries/Game.php');
class Main extends CI_Controller {
...
}
Upvotes: 0
Reputation: 2125
Another option I found is that you can store your object in the form of session array values:
You can store it like this:
$this->session->set_userdata($yourObject);
Access like this:
$this->session->userdata['property name of your object'];
Upvotes: 0
Reputation: 1024
Unfortunately, php does not allow you to serialize references to one object from another. This is why when you restore your object it does not contain the data it started with.
The best solution I have come up with is to create a Session object in my model layer which is restored using a cookie. The session table in your database handles the references to the objects that you would otherwise have serialized. Once your Session model is loaded, you can use it to load the 'session stored' objects, eagerly or lazily.
Further, should these objects hold references to other model objects you can use the same principle to traverse the rest of the model layer, based on the relational references. This can seem daunting, but there are a number of ORMs you could check out if you dont feel comfortable implementing it yourself.
Upvotes: 4