How to use the $user->data property in Drupal 7

Everything you need to know about how to use the highly performant $user->data property whilst maintaining data integrity with a bit of best practise Single Responsibility Principle and Single-Entry, Single-Exit thrown in for good measure.


Drawbacks of using Field API


Download the example module

If you don’t feel like reading everything below, then feel free to jump on to the Github at https://github.com/martsie/drupal-user-data-example/ and check out the code.


The Solution: $user->data

The Drupal user object has a little known field automatically attached to it called ‘data’ which stores serialised settings for each user object in the database.

Advantages

Disadvantages


Don’t store and access complex objects in $user->data directly

Although the data property is lightweight it can be abused pretty easily by adding large data sets.

Lets break down, line by line, why the above example is wrong.


OOP to the rescue

Using classes to access and set objects in the data array is a great way of overcoming the issues in the previous section and keeping code clean, maintainable and test-able. Here’s what we want to be able to do:


Some features of the class

Yes there’s a lot of boilerplate code and PHP doc commenting but what’s affectively happened is we’ve create an API specific to the user data you’re storing! You can read more about SRP and SESE in Clean Code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).


Connecting with Entity Metadata Wrappers

The next logical step is to integrate the above class with Entity Metadata Wrappers, especially if it’s something you already use in your projects. The problem with Entity Metadata Wrappers however is that they’re not available at hook_boot (which is where, especially if you’re operating beneath a heavy cache, you’ll want to do some of your user reactions) and they can get difficult to use in an IDE that has class method autocompletion. Using Meta Data Wrappers we’ll be able to achieve the following level of abstraction…

The code to retrofit entity api below is quite simple and, because of the strict nature of the EmployeeDetails class, there shouldn’t be too many surprises when retrofitting the metadata properties for the other values.


Download the example

If you’re keen on doing some user data manipulation you can download the entire example at:https://github.com/martsie/drupal-user-data-example/ You don’t need to go as far as the Entity API abstraction, especially if you’d like to keep things low level and accessible in hook_boot however the important thing to understand is that even data stored in a serialized format can be stored and retrieved in a structured, strict and testable manor.