Saving User data in concrete5

Saving User data in concrete5

There are a couple of ways to store information about a User in concrete5. What are they and which method should you choose?

Article by Ollie / / Comments / Difficulty 
Saving User data in concrete5

When we think about saving user information in concrete5, we naturally think of concrete5's userInfo object and custom user attributes. This approach is great, and certainly the best way of describing our user. Let's look at a quick example which allows us to save data about a user to a custom user attribute called 'Favorite Animal', which has an attribute handle of 'favourite_animal':

$u = new User();
$ui = UserInfo::getByID($u->getUserID());
$ui->setAttribute('favorite_animal', 'Dog');

As you can probably see, we've stored the value of 'Dog' in our custom attribute for the currently logged in user. To retrieve later we'd do something similar but we'd use the userInfo::getAttribute() method instead, like this:

$u = new User();
$ui = UserInfo::getByID($u->getUserID());
echo $ui->getAttribute('favorite_animal');

To clear it we'd issue the following method call:


So that is basically how we store user information using custom attributes and the userInfo object. Straightforward enough?

Sometimes though, we need to store information for a user which isn't really data which describes our user. For example, we may have application preference or configuration data. Imagine our user being able to set options which tailor his experience of our application, in such a scenario we may use concrete5's config object instead of the userInfo object.

Starting with the basics, to save application data in general, we would do something like this:

config::save('custom_logo', 'logo.png');

Note, there's no user association here - this is application level configuration data.

To access this configuration data we'd use the following method:

echo config::get('custom_logo');

And, we can unset the configuration key using config:clear($key).

Really simple yes? And it's no more difficult to store configuration data for the user in your application. Consider this example, where our user can customise the background color of his control panel:

$u = new User();
$u->saveConfig('background_color', 'red');

To retrieve a user's background color preference, we simply access the configuration key like this:

$u = new User();
echo $u->config('background_color');

That's it! Now you can store user information as user attributes using the userInfo object, and application preference data for users without cluttering up your userInfo object, using the config object.

Join the conversation

comments powered by Disqus