When should I use setUserState in Joomla?
Asked Answered
T

1

10

DETAILS

I can use user state variables to store and retrieve data in Joomla sessions.

EXAMPLE set variable

$app =& JFactory::getApplication();
$app->setUserState( 'myvar', $myvarvalue );

but I can also store and retrieve variables in session using JFactory/getSession.

EXAMPLE set variable

$session =& JFactory::getSession();
$session->set('myvar', $myvarvalue);

QUESTIONs

What is the difference between the two methods? When should I use one over the other?

Teleplay answered 2/11, 2012 at 13:29 Comment(0)
E
10

In short: it's not a big difference and you can use whatever feels right in the context. I would stick with JApplication/setUserState because I think the code is better self explanatory.

The actual difference:

Both methods will store the specified state in the session. JApplication/setUserState will in fact internally use JSession/set to store the state.

What JApplication/setUserState does differently is that it will store every key value pair in a JRegistry. So it is equal to:

$session = JFactory::getSession();
$registry = $session->get('registry');
$registry->set('myvar', $myvarvalue);

So what's the point of using a JRegistry? It's the pretty much the functionally provided JRegistryFormat. You can use it to both parse and format the state:

$session = JFactory::getSession();
$registry = $session->get('registry');
$json = $registry->toString('JSON');
$xml = $registry->toString('XML');

It's also worth pointing out that using JApplication/setUserState your state will end up in the "default" namespace:

$app = JFactory::getApplication();
$app->setUserState( 'myvar', $myvarvalue );
// $_SESSION['default']['registry']->set('myvar', $myvarvalue)
Ebonee answered 2/11, 2012 at 14:31 Comment(1)
Thanks for the detailed answer! I feel I understand the differences/similarities now :)Teleplay

© 2022 - 2024 — McMap. All rights reserved.