Implementing the Model
In
the
rest of this chapter, we’ll lay out the code that
implements a robust Model for a class we’ll call
Publisher
. For
the sake of simplicity, each publisher has just two attributes: an ID
and a name. The id field is the primary key and
uniquely identifies each row of the table. The
Name field is the name of the publisher.
In this class, you will recognize all the methods we discussed in the previous section. Of the 13 methods, 4 correspond directly to SQL activities:
-
create( ) An instance method that inserts a new row into the table to hold the data from this object. The primary key for this table is a MySQL
AUTO_INCREMENTfield that automatically creates a new value for that field. Therefore, this method inserts only the value of thenamefield. Theidfield is passed in by this method asNULL, set in the database by MySQL, and then retrieved and assigned to the object’sidattribute by this method.-
get( ) A static method that creates an SQL
SELECTstatement based onWHEREparameters passed to the function. For each row of the result set, a new object is created and an array of these objects is returned. This method represents the Generic Where method described in the previous section.-
remove( ) An instance method that removes the row of data corresponding to this object in the database. It issues an SQL
DELETEcommand to accomplish the removal. After this method is called, the program should destroy the object, because its underlying data is ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access