2

I’m working on a simple cart and trying to utilize the user session id to keep track of things.

The session getting saved to the database doesn't match the session that’s being displayed in templates. I have a template variable set-up to output the session on the front end for comparison.

There’s quite a bit of code with a plugin so I’ll include what’s most relevant.

I have a service setup that included methods for saving an item and loading a session through a variable. In the service constructor the session is set like so:

class EyeCart_CartService extends BaseApplicationComponent
    {
    private $_cartSession;

    public function __construct()
    {
        $session = new  HttpSessionService;
        $session->open();
        $this->_cartSession =  $session->sessionID;
    } 
    etc.

I then use _cartSession in the saveItem method. This works fine.

public function saveItem(EyeCart_CartModel $item)
{
    ….
    // Set the cart record attributes
    $cartRecord->session = $this->_cartSession;  // the session saves as bakg59bu9lmbbs50s8meg5jk71
    $cartRecord->itemId = $item->itemId;
    etc…

In the service I also have a cartSession method for outputting the current session in the template via variables (for testing).

public function cartSession()
{
   return $this->_cartSession;
}

This returns a different value than is being saved in the database (9m9g3msjo3v9f8ke7gf4b3qfv0). I tried including the cart variable on different templates and it displays consistently across page states just not when saving to the db.

Any advice?

2

I suspect you're getting different session IDs because you're creating a new instance of HttpSessionService (which ultimately is a wrapper for PHP's session handling).

What you should be doing is using Craft's existing session off of craft()->httpSession and grab the existing PHP session ID with craft()->httpSession->getSessionID().

No need to call craft()->httpSession->open(), because Craft will automatically start the session as soon as the HttpSessionService gets loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.