Model-View-Controller
From CunningPlans
Model, View, Controller is a pattern for separating the major areas of functionality of a software project. Like other application frameworks, Baldrick enables and encourages this style of programming.
For a detailed introduction, see the Wikipedia article Model-view-controller.
Contents |
[edit] MVC in Baldrick
[edit] Model
The Model consists of the Module author's classes to represent the logic of the application. These classes (not part of Baldrick) are such things as a Shopping Cart (and cart items), Message Board (and board postings), etc.
One simple Model used by most applications is an entity that is loaded from a database record, modified, and saved back to the database. Baldrick::SpecialTurnip provides one implementation of this.
[edit] Controller
The Controller is your Module's subclass of Baldrick::Dogsbody. These classes are loaded as needed by Baldrick::App, and the requests dispatched to each. The run() method of Baldrick::Dogsbody then invokes the appropriate handle function of the Dogsbody, based on the user's command.
[edit] View
The View is provided by the TemplateAdapter family of classes. These produce output (web pages, files, email) using any of several template languages - currently Template Toolkit and Text::Template are supported. To make a "Model" object available to the template system, use the addObject() method of the TemplateAdapter.
[edit] Example
The Dogsbody class (a Controller) that implements a Module ties the three types of components together. This generally happens in the handle functions.
package MyCart::MyAppDogsbody;
sub handleAddToCart
{
my ($self, %args) = @_;
my $request = $self->getRequest();
# set up the Model object.
my $cart = new MyCart::ShoppingCart();
$cart->load( session => $self->getSession() );
# Manipulate it.
my $rc = $cart->add(productid => $request->get("productid"));
# send one of several Views
if ($rc < 0) # ERROR
{
$self->sendOutput(error => $cart->getError());
} else {
# Make model available to view
$self->getOut()->addObject($cart, "cart");
$self->getOut()->addObject($cart->getItemAdded(), "newitem");
# and send it to user.
$self->sendOutput(template => "added-item");
}
}
