0

I am building a shopping cart using the Yii framework. I have created a cart model to store the items the user adds to the cart, and I'm keeping track of the products that guest shoppers are adding to the cart by using a session_id field that stores the current session.

However, if the shopper abandons the cart or the session simply times out before they proceed to the checkout I find that I have a bunch of records in the cart table that need to be cleaned up.

I was thinking that the best way to do this would be to piggy back on the garbage collection process that Yii uses to clean up the session table, but I'm not sure how to do this, or even if this is the best way.

Am I on the right track here?

If so, how do I go about piggybacking on Yii's garbage collection?

John Judd
  • 750
  • 7
  • 22
  • your best bet would probably be to run a cron job. you might even want to collect some stats on that data as well before purging it. – ldg Oct 03 '11 at 04:42
  • Using a cron job is certainly an option. But I was hoping to be able to use Yii's functionality to handle this. That should make collecting stats even simpler. – John Judd Oct 04 '11 at 07:22

1 Answers1

2

I don't know much about PHP's session garbage collection, so I don't know if this is a better way to go than a cron job. The little I do know I just learned from Professor Google, and it makes me think relying on the session garbage collection may not be as reliable as you want:

How do I expire a PHP session after 30 minutes?

But it could work, I suppose. Kind of clever, actually, if it does. And in this case, you would need to override the gcSession() method in the CDbHttpSession class in the Yii core (assuming, as you say, you are using the database session storage). You can override this method very easily, actually, in your config.php file.

First, create your new MyCustomHttpSession class which extends CDbHttpSession (drop it in your /components folder probably). Be sure to add your new custom Cart garbage collection to the gcSession() function!

class MyCustomHttpSession extends CDbHttpSession
{
  public function gcSession($maxLifetime) {
    /**** ADD YOUR CUSTOM LOGIC HERE ****/
    $sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
    $this->getDbConnection()->createCommand($sql)->execute();
    return true;
  }
}

Then, tell Yii to use your new MyCustomHttpSession class in the components configuration array:

'components'=>array(
  'session'=>array(
    'class' => 'application.components.MyCustomHttpSession',
    'connectionID' => 'db',
    'timeout'=>14400, // 4 hour session time
  ),
),

I did not test this, but it should work just fine. Good luck!

Community
  • 1
  • 1
thaddeusmt
  • 15,410
  • 9
  • 67
  • 67