问题
I have a cart application with unique items with qty 1 - I need to deplete the stock qty when a user puts one in the basket to avoid someone else buying it. Problem is, that if they abandon the cart without buying I need to put the item back in stock.
Is there a way I can replenish the stock when the cart session expires? ie run a script to replace the stock.
回答1:
You can use session_set_save_handler
to create a custom session-handling class.
When you do this, you can decide other actions that need to run either when the garbage collector is called or at session destroy. If you decide to work with the garbage collector, ensure that you also know the values for session.gc_divisor
and session.gc_probability
and also understand what they do (these set the probability that the garbage collector will run).
回答2:
To avoid the need of cron jobs; keep it simple:
- A user picks places a object in his/hers basket
- Timestamp for "placing object in basket" is stored in the database, and a timeout timestamp is stored too. For example
(time() + (60*20))
- User closes webpage
- On every pageload you do a simple mysql-query to check if timeout-timestamps are smaller than the current timestamp. If the query returns a result, delete from basket and put back in slot.
(This require that you update some sort of "last activity" in the database too)
Should be pretty straight forward.
回答3:
Create a database table to track session activity, say sessions
. In it, put at least the fields session_id
and a DATETIME or TIME field called last_activity
.
If you don't have so already, also create a carts
table that holds the content of the cart (like product_id
and quantity
) and has a link to the session_id
. Then, there are 2 scenarios:
- The user finishes the order, just "wipe" the rows in the
carts
table belonging to their session. - The user abandons the cart, call a cronjob that checks to see if the
last_activity
value is more then you want it to be (say, more then an hour ago). Make that script re-stock your supply with the quantity that was in the cart.
Note that you will need to update the last_activity
field in your bootstrap/loader (a mechanism that is triggered on every loaded page).
来源:https://stackoverflow.com/questions/8416159/php-run-a-script-when-a-session-expires