Going native with WooCommerce sessions
WooCommerce comes complete with its own database-backed session handler. Information about the shopper, the contents of their cart, any flash messages that need to be displayed (and potentially lots more) is stored by this system.
A typical chunk of session data might look something like this:
{
"cart": {
"a8f15eda80c50adb0e71943adc8015cf": {
"key": "a8f15eda80c50adb0e71943adc8015cf",
"product_id": 1234,
"quantity": 1,
"line_total": 123.45,
}
},
"cart_totals": {
"shipping_total": "0",
"discount_total": 0,
"total": "123.45"
},
"applied_coupons": {},
"coupon_discount_totals": {},
"coupon_discount_tax_totals": {},
"removed_cart_contents": {},
"wc_notices": null,
"customer": {
"id": "123456",
"date_modified": "2023-03-28T12:36:01-07:00",
"address_1": "987 Test Avenue",
"address_2": "Box 345",
"state": "BC",
"country": "CA",
"first_name": "Tom",
"last_name": "Thumb"
}
}
The above is a simplification. For readability, I've removed various fields and used JSON formatting (whereas WooCommerce actually uses PHP's native serialized data format).
So why did WooCommerce 're-invent the wheel', instead of using PHP's own built-in session handling capabilities? I would assume it is for the following reasons:
- Though PHP's sessions implementation is extremely flexible (custom session handlers can be registered), by default it writes session data to the file system—specifically, the system's temporary directory—and on some deployments, such as multi-node deployments, this could be problematic.
- WordPress plugins like WooCommerce can't really assume too much about the hosting environment (trusting that the host or the site operator has tuned PHP's session handling accordingly is probably a bad idea).
- Registering its own session handler with PHP is also problematic: what if another plugin wants to do the same thing? What if the host has already configured their own handler?
So, it provides its own implementation which runs beside the one provided by PHP (an alternative, not a replacement) and that is the one it prefers.
WooCommerce is itself extremely flexible, though, and we can in turn replace its session handler with one of our own. We could for instance create a handler that stores session data in Redis. Over here is a (rough and largely untested) example of registering one such session handler, which makes WooCommerce use native PHP sessions. Isn't this a step backward? Why would we do this?
- We may already have a preferred session handling mechanism that registers itself with PHP. This would let us take advantage of that.
- Or, in some circumstances, we might simply find that the performance characteristics of native PHP sessions are more to our liking (vs the default database backend provided by WooCommerce).
- Or, it could simply be a starting point for something else (maybe that Redis backend?).