After looking around the internet for days, i decided to ask your help here.
I got a problem with Zend Framework 2 session container management. I don't understand why, but the framework emptied all my containers each time i'm changing page.
My case is simple, i'm building an online shop :
- The customer is on a product and click the "add to cart" button
- The product is saved to session
- The customer get back to the products list to choose another product ... but there is no product anymore in his cart.
Here is a piece of code :
// Create container to add product
$container = new Zend\Session\Container('frontCart');
// Add product to cart
$container->offsetSet('frontCartContent',
array(1 => serialize($my_product_object));
If i make a debug of the session just after added :
Debug::dump($_SESSION);
// Display this :
["frontCart"] => object(Zend\Stdlib\ArrayObject)#70 (4) {
["storage":protected] => array(1) {
["frontCartContent"] => array(1) {
[1] => string(1175) "my serialized product object"
}
}
["flag":protected] => int(2)
["iteratorClass":protected] => string(13) "ArrayIterator"
["protectedProperties":protected] => NULL
}
Then, if i simply reload the page, or if switch from :
http://mydomain.com/products_list/my_product
to
http://mydomain.com/products_list
I get :
Debug::dump($_SESSION);
// Display this :
["frontCart"] => NULL
Please, help :-( I don't understand at all why ZF2 has this behavior, and this is very problematic for an online shop customer if he can't add and by products.
Thx
EDIT
Following Tim's demand here is more code.
I initialize my session container in the controller's constructor
public function __construct()
{
if (!$this->sessionCart)
{
$this->sessionCart = new Container(ConstantSession::FRONT_CART);
}
}
Then, here is the exact way i'm adding the product to the container
$this->sessionCart->offsetSet(ConstantSession::FRONT_CART_CONTENT,
array($cartNumber => serialize($product))
);
$cartNumber is incremented following the number of products in the cart (when it'll work). $product is an object with all its properties.
EDIT 2
Following Tim's advises i changed my "add to cart" code to :
$this->sessionCart->frontCartContent = array($cartNumber => $product);
When i want to get back my session content i create a new instance of Container :
// Init new container
$container = new Zend\Session\Container('frontCart');
// Get the content
$container->frontCartContent;
If i make a Debug::dump() of the last line, i still get NULL after changing page.