Yii:利用会话 GC 进行购物车清理?
我正在使用 Yii 框架构建一个购物车。我创建了一个购物车模型来存储用户添加到购物车的商品,并且通过使用存储当前会话的 session_id 字段来跟踪访客购物者添加到购物车的产品。
但是,如果购物者放弃购物车或会话在结账前超时,我会发现购物车表中有一堆记录需要清理。
我认为最好的方法是利用 Yii 用来清理会话表的垃圾收集过程,但我不确定如何做到这一点,或者即使这是最好的方法。
我走在正确的轨道上吗?
如果是这样,我该如何利用 Yii 的垃圾收集呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 PHP 的会话垃圾收集了解不多,所以我不知道这是否是比 cron 作业更好的方法。我所知道的一点点是我刚刚从 Google 教授那里学到的,这让我觉得依赖会话垃圾收集可能并不像你想要的那么可靠:
如何在 30 分钟后使 PHP 会话过期?
但我想它可以工作。如果确实如此的话,实际上有点聪明。在这种情况下,您需要重写 Yii 核心中 CDbHttpSession 类中的 gcSession() 方法(假设,正如您所说,您正在使用数据库会话存储)。实际上,您可以在 config.php 文件中非常轻松地覆盖此方法。
首先,创建新的 MyCustomHttpSession 类,该类扩展 CDbHttpSession(可能将其放在 /components 文件夹中)。 请务必将新的自定义 Cart 垃圾收集添加到 gcSession() 函数中!
然后,告诉 Yii 在组件配置数组中使用新的 MyCustomHttpSession 类:
我没有对此进行测试,但它应该可以工作很好。祝你好运!
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!
Then, tell Yii to use your new MyCustomHttpSession class in the components configuration array:
I did not test this, but it should work just fine. Good luck!