So, the long winded, old-school Variable-Tracing form of the logic is this:
1: Initial Trigger
Let us assume there are 4 offers active in our database. With ID’s 1,2,3 and 4.
The user has just signed up. We assign a cookie to this user, shown_offers
, which contains the string “0”.
2: Initial Load
The user reloads the page (or we do it for him, whatever.)
Our cookie-sniffing PHP code says “Ah. This user has a cookie, we should look for an offer to serve them.”
PHP takes the string “0”, explodes it. This returns an array, [“0”]
That array has a map run over it, passing each value to the intval
function. For sake of brevity, I believe we can all understand what that function does, and thus the map function returns [0].
Implode then smashes the array back into a string, “0”.
Yes, this is the same string as before. But now we know for certain, because intval can only return integers, that the string contains only numbers and commas. No malicious code, no strings, no weirdness. So it’s safe to hand to our database execution engine.
We tell the database "Find me an offer, that is active, but is not in the set “0”. Give me only 1 of them, and make it the highest offer ID. Database does its thing, and spits back an answer: 4.
We serve Offer 4 to the user.
3: User has closed an offer.
We served offer 4 to the user. He’s seen it, and closed it. We append “,4” to the cookie, making it now read “0,4”.
4: User has reloaded the page again.
Our cookie-sniffing PHP code says “Ah. This user has a cookie, we should look for an offer to serve them.”
PHP takes the string “0,4”, explodes it. This returns an array, [“0”,“4”]
That array has a map run over it, passing each value to the intval
function. The map function returns [0,4].
Implode then smashes the array back into a string, “0,4”.
We tell the database "Find me an offer, that is active, but is not in the set “0,4”. Give me only 1 of them, and make it the highest offer ID. Database does its thing, and spits back an answer: 3.
We serve Offer 3 to the user.
Use case: We added an offer, 5.
Well we added an offer. It’ll have a higher offer_id. So the next time the user with the cookie comes back, the system will process the code, and hand the user that offer first. Offer 5 is shown to the user.
Use case: We deactivated an offer the user has not seen. (Offer 2)
Then the query won’t find that offer the next time the user comes to the site, because it no longer matches the isActive = 1
clause. The query will find the next active offer that hasn’t been shown to the user, and show them Offer 1.
Use case: We deactivated an offer the user has seen.
Then the query won’t find that offer the next time the user comes to the site, both because it no longer matches the isActive = 1
clause AND the offer id would be in the set of already-seen offers.