O'Reilly logo

Managing & Using MySQL, 2nd Edition by Hugh E. Williams, Randy Yarger, George Reese, Tim King

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Example of the Model’s Use

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 Publisher class:

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.

$pub->setName("Joe's Boks");

Note that we didn’t set the id 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:

$pub->create(  );

Now the object has been created in the database and can be retrieved ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required