Monday, October 29, 2007

Object Oriented ASP: Using Classes in Classic ASP

The Class:

**************cBook.asp********************
< %
Class cBook

'Private, class member variable
Private m_ID

'Read the current ID value
Public Property Get ID()
ID = clng(m_ID)
End Property

'store a new ISBN value
Public Property Let ID(p_Data)
m_ID = p_Data
End Property

'############# Public Functions, accessible to the web pages ##############
'Loads this object's values by loading a record based on the given ID
Public Function LoadFromId(p_Id)
dim strSQL, MyID
MyID = clng(p_Id)
strSQL = "SELECT * FROM Book WHERE (lngBookID = " & MyID & ") "
LoadFromId = LoadData (strSQL)
End Function

Private Function LoadData(p_strSQL)
dim rs
set rs = LoadRSFromDB(p_strSQL)
LoadData = FillFromRS(rs)
rs. close
set rs = nothing
End Function

'Takes a recordset
'Fills the object's properties using the recordset
Private Function FillFromRS(p_RS)
select case p_RS.recordcount
case 1
Me.ID = p_RS.fields("lngBookID").Value
case -1, 0
'err.raise 2, "Item was not found"
case else
err.raise 3, "Item was not unique"
end select
End Function

public Function Save()
Dim strSQL
'If the book has an existing (Autogenerated!) ID, then run an insert
if Me.ID < 1 then
Me.ID = InsertRecord("Book", "lngBookID", ...)
'Otherwise run an update
else
strSQL = strSQL & " UPDATE Book SET ... where lngBookID = " & Me.ID
RunSQL strSQL
End if
Save= Me.ID
End Function
End Class
% >

**************cBooks.asp********************
Class cBooks
'Private, class member variable
Private m_Books

Sub Class_Initialize()
set m_Books = Server.CreateObject ("Scripting.Dictionary")
End Sub
Sub Class_Terminate()
set m_Books = Nothing
End Sub

'Loads all books into the library
Public Function GetAllBooks()
dim strSQL
strSQL = "SELECT * FROM Book "
GetAllBooks = LoadBookData (strSQL)
End Function

Private Function LoadBookData(p_strSQL)
dim rs
set rs = LoadRSFromDB(p_strSQL)
FillBooksFromRS(rs)
LoadBookData = rs.recordcount
rs. close
set rs = nothing
End Function

'Takes a recordset
'Fills the object's properties using the recordset
Private Function FillBooksFromRS(p_RS)
dim myBook
do while not p_RS.eof
set myBook = New cBook
myBook .ID = p_RS.fields("lngBookID").Value
myBook .Title = p_RS.fields("strTitle").Value
m_Books.Add myBook.ID, myBook
p_RS.movenext
loop
End Function

End Class

**************default.asp********************
Dim myBook
Set myBook = New cBook
myBook.ID = ...

**************edit_book.asp********************
Dim myBook
Set myBook = new cBook
myBook.loadById(request("bookid"))
myBook.Title = Request.Form("title")
myBook.Save

No comments: