Yes, the API did change a slightly.
In the older version, sessions were written on every page load, regardless if the data changed in them at all. I worked with some other developers to fix this so that sessions are only written if something changes.
In an ideal (i.e. high-traffic environment), this is what happens:
- When a new visitor hits your site, a new session is created for them and stored in the database. The session ID, exipiration, and “variant” is stored in a cookie in the user’s browser.
- When the user comes back to the site, the session is read into the cache (APC or Memcached or something else, depending on your configuration) if it’s still valid.
- If the session is unexpired, but past the timestamp recorded as a variant, the expiration is updated so things aren’t cleared out too quickly (This is 1 database write to update the exipiration. But it won’t occur on every page load … and you can set the timeout before it does happen through a filter.
- If nothing changes during this page load (i.e. nothing added to a cart, no options changed), then nothing further happens.
- When the user revisits your site, the session is loaded from the cache (no roundtrip to the database).
- If any session data changes, the session is marked as “dirty.”
- Dirty sessions are re-written to the database at the end of the request.
One big change did occur with the update – sessions are no longer explicitly available in the global namespace as $wp_session
. Instead, you’ll need to:
- Explicitly define
$wp_session = WP_Session::get_instance();
inside any session-dependent functions.
- OR set a global
$wp_session
equal to WP_Session::get_instance()
inside a function hooked to either init
or wp_session_start
.
The reasoning behind this change was primarily to keep the global namespace clean and to prevent installing any hidden dependencies in code. A lot of people freaked out that WP_Session was implemented as a singleton in the first place. A second chorus protested to storing it in a global variable as well. This qas a compromise.