User State Variables in Joomla
Joomla has a built in functionality to make it easy for developers to store and retrieve variables that are stored with the session. There are two ways to set user state variables.
Method 1: Application::setUserState
$app = Factory::getApplication();
$app->setUserState('com_planets.state1', 'state1');
The first parameter is the key under which to store the variable. The second parameter is the value to store with the state variable.
Method 2: Application::getUserStateFromRequest
$app = Factory::getApplication();
$stateVar = $app->getUserStateFromRequest('com_planets.state_variable', 'state_variable', 'state1');
This method will update the user state variable by looking in the variables that were passed with the request (in either GET or POST) and updating the user state variable if the specified request variable is set.
This can be used to set user state variables with values that are passed from forms. If an existing value can be found either in the request or in the stored state variable, this is returned. Otherwise, the specified default value is returned (if it is specified), or NULL is returned if no value can be found.
Method 3: Application::getUserState
$app = Factory::getApplication();
$stateVar = $app->getUserState('com_planets.state_variable', 'state1');
This method will retrieve the value of the specified user state variable. If this user state variable has not been set, then the value is read from the default parameter. If the user state variable has not been set and default is not specified, the method will return NULL.