Global $user is gone from Drupal 8

To help people keep abreast of what's new in Drupal 8 core, a few volunteers are providing a semi-regular update with summary details of changes. One of the notable points that crept in a few weeks ago was that the global $user object has gone!

In other versions of Drupal, PHP globals are used to store a lot of state that wildly different function scopes might need to access. However, the preferred method in Drupal 8 for accessing such shared state is services: these avoids many of the problems associated with globals. Using a service, which itself hangs off the \Drupal namespace, is a much more robust way of retrieving such shared data.

Here's how D8 now works, in two lines of executable code:

// This code returns the current user ID.
$account = \Drupal::currentUser();
return $account->id(); 

Without wanting to rehash crell's succinct change record completely in this blogpost, Drupal 8's conventions also clarify what you're actually getting from the service: the return value is a UserSession object, descriptive of the session of the user making the current page request, rather than describing the abstract concept of that user regardless of their current login state.

It's been really useful for me to be able to occasionally dip into the stream of D8 changes, and learn what I feel comfortable learning in the time available. If you're still reading this, then I think you might find it useful too, and you should definitely subscribe to the D8 updates, in your feed reader of choice. There's also a Twitter account, which tracks the feed of recently published change records, but note that it uses date of publication of the change record, not date of closure of the related ticket.