Friday, March 30, 2007

MVCの練習 perl

---index.cgi-----
#!/usr/local/bin/perl

use strict;

use Controller;

Controller->new->dispatch('index');# Sledge風にしてみました。
----Controller.pm -----

package Controller;
use strict;
use CGI;
use Model;
use View;
use Error qw(:try);

sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}

sub dispatch {
my $self = shift;
my $page = shift||'index';
print "Content-Type: text/html;\n\n";
try {
my $q = new CGI;
my $color = $q->param('color')||'white';
my $model = new Model($color);
my $view = new View;
if ($model->get_RGB){
$view->hit_page($page,$model->get_RGB);
}else{
$view->not_found_page($page);
}
}catch Error with {
my $e = shift;
warn "system error: " . $e->text;
} finally {
;
}

}
1;

----Modal.pm-----

package Model;
use strict;

sub new {
my $class = shift;
my $self = {};
$self->{color} = shift;
bless $self, $class;
}


sub get_RGB {
my $self = shift;
if ($self->{color} eq "white"){
return "#FFFFFF";
}else{
return "";
}
}


1;

----View.pm------
package View;
use strict;

sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}

sub not_found_page {
my ($self, $str) = @_;
print $str,"not found\n"
}

sub hit_page{
my ($self, $page,$str) = @_;
my $out = sprintf("page :%s, str :%s\n",$page,$str);
print $out;
}

1;

---

No comments: