Now that we’ve seen the Model class and all its supporting classes, let’s look at how it is used in practice. The following snippets of code would be part of the Controller layer of the application: the layer that performs all the logic. Note how all the actual database calls are hidden from this layer. It uses just calls to the Model class.
Each file in the Controller layer indicates that it will use the
use CBDB::Publisher; my $VERSION = 1.0;
A new object is created as follows:
my $pub = new CBDB::Publisher( );
Now let’s set some data. The following creates a new publisher in our program (but not the database). We’re in a hurry, so we can’t be bothered with good spelling.
Note that we didn’t set the
field of the publisher. The ID is an auto-increment field taken care
of automatically by the database. A more abstract way of
understanding our approach is that the ID is not a real-world
property of this object. It exists only because the object-relational
model we’re using internally requires it. Therefore,
at the controller level, we don’t have to worry
about assigning it or making sure it’s unique.
We’ll see what we just created:
print 'Our new publisher is ' . $pub->getName( ) . "\n";
If the program were to terminate at this point, this object’s data would be lost. To make it persistent, we need to save it to the database:
Now the object has been created in the database and can be retrieved ...