User specific login information is usually stored in session variables in any web application. However, Flex doesnt have anything called session variables in it. So how do we save this information across the whole application. Static classes come to the rescue here. This can also be achieved by use of shared objects and Singletons but I am going to focus on static classes for now.
A static class holds the information in it once declared and is very useful for such scenarios. Typically, after you are done with the username/password authentication in your Flex app, you would need to store the data in a static class to be able to access it from anywhere in your application.
Here is how we do it:-
1 package classes.UserInfo
2 {
3 public class UserInfo
4 {
5 private static var myUserName:String = "";
6 private static var myFullName:String = "";
7
8 public static function get UserFullName():String
9 {
10 return UserInfo.myFullName;
11 }
12 public static function set UserFullName(param:String):void
13 {
14 UserInfo.myFullName = param;
15 }
16 public static function get UserName():String
17 {
18 return UserInfo.myUsername;
19 }
20 public static function set UserName(param:String):void
21 {
22 UserInfo.myUserName = param;
23 }
24 public static function getInstanceMemento():Object
25 {
26 var o:Object = {
27 myUserName: UserInfo.myUserName,
28 myFullName: UserInfo.myFullName
29 };
30 return o;
31 }
32 public static function setInstanceMemento(param:Object):void
33 {
34 UserInfo.myUserName = param.myUserName;
35 UserInfo.myFullName = param.myFullName;
36 }
37 }
38 }
Once you have the class ready, you can use it to set the values. First , import the class you wrote in your mxml file.
import classes.UserInfo;
Then, after you are done with your authentication process, you can set the values :-
UserInfo.myUserName = "joebloggs"; UserInfo.myFullName = "Joe Bloggs";
and you can read this information anywhere in your application this way :-
UserInfo.myFullName
or you can use the getInstanceMemento() or setInstanceMemento() to do the above in one go!
Obviously, you can expand this class to include a lot of other informaion related to the user e.g. email, phone, fax etc and use it wherever required.