Controller

malte on 2003-04-03T11:07:30

A controller is probably a different beast than you expect (if you have a Smalltalk background). First, it's a singleton. There is only one for any perl process. It thus shouldn't have per request state. The main role of the controller is that of a dispatcher. For every request it decides what to do, meaning it finds the appropriate model, view and template. Afterwards it creates the model ands paints the view.

So much for the controller basics. The real fun begins if you stack them using the Decorator pattern. Websites sometimes have restricted parts, so you might have an AuthorizingController, or you might want to keep states between requests, so you have a StatefulController.

The standard ENGINE::MVC::Controller::Authorized class looks like this:

<
package ENGINE::MVC::Controller::Authorized;
use strict;
use Carp;
use base "ENGINE::MVC::Controller::Delegation";

# execute action
sub execute {
	my($self,$q, $action) = @_;
	
	$action = $self->delegate->get_action($q, $action);
	
	$action = $self->authorize($q, $action);
	
	$self->delegate->execute($q, $action);
}

# 
sub authorize {
	my($self, $q, $action) = @_;
	
	return $action;
}

It intercepts the delegates execute method and filters the action through its authorize method (subclasses may decide to do something more useful than just returning the action).

Let's go back to the main application, that was introduced in the first part of this article. You can now turn the controller into an authorized controller:


our $AuthorizedController;

$AuthorizedController ||= ENGINE::MVC::Controller::Authorized->new($Controller);
$AuthorizedController->execute($q);

That's the controller, templates are next.