Share via


Data Storage with Objects

In object-oriented languages, a class offers a useful and convenient vehicle for storing data and procedures related to an entity. For example, you could define a customer class to hold information about a customer as well as a method to calculate the customer's age:

DEFINE CLASS customer AS CUSTOM
   LastName = ""
   FirstName = ""
   Birthday = { - - }
   PROCEDURE Age
      IF !EMPTY(THIS.Birthday)
         RETURN YEAR(DATE()) - YEAR(THIS.Birthday)
      ELSE
         RETURN 0
      ENDIF
   ENDPROC
ENDDEFINE

However, data stored in objects based on the customer class are stored only in memory. If this data were in a table, the table would be stored on disk. If you had more than one customer to keep track of, the table would give you access to all of the Visual FoxPro database management commands and functions. As a result, you could quickly locate information, sort it, group it, perform calculations on it, create reports and queries based on it, and so on.

Storing and manipulating data in databases and tables is what Visual FoxPro does best. There are times, however, when you'll want to store data in objects. Usually, the data will be significant only while your application is running and it will pertain to a single entity.

For example, in an application that includes a security system, you would typically have a table of users who have access to the application. The table would include user identification, password, and access level. Once a user has logged on, you won't need all the information in the table. All you need is information about the current user, and this information can be easily stored and manipulated in an object. The following class definition, for example, initiates a logon when an object based on the class is created:

DEFINE CLASS NewUser AS CUSTOM
   PROTECTED LogonTime, AccessLevel
   UserId = ""
   PassWord = ""
   LogonTime = { - - : : }
   AccessLevel = 0
   PROCEDURE Init
      DO FORM LOGON WITH ; && assuming you have created this form
         This.UserId, ;
         This.PassWord, ;
         This.AccessLevel
      This.LogonTime = DATETIME( )
   ENDPROC
* Create methods to return protected property values.
   PROCEDURE GetLogonTime
      RETURN This.LogonTime
   ENDPROC
   PROCEDURE GetAccessLevel
      RETURN This.AccessLevel
   ENDPROC
 
ENDDEFINE

In the main program of your application, you could create an object based on the NewUserclass:

oUser = CREATEOBJECT('NewUser')
oUser.Logon

Throughout your application, when you need information about the current user, you can get it from the oUser object. For example:

IF oUser.GetAccessLevel( ) >= 4
   DO ADMIN.MPR
ENDIF

See Also

Writing Class Definitions Programmatically | Arrays of Members and Objects | Object and Data Integration | Object Reference Creation | Object-Oriented Programming