Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Saturday, June 14, 2008

MVC コントローラー URLによる動的にモジュールを呼ぶ

----- test.php
<?php

/*
e.g
test.php/c=user_proile/m=register/

*/

$path_info = explode('/', $_SERVER['PATH_INFO']);
while(list($cnt,$path) = each($path_info)) {
if ($path == "") continue;
list($key,$value) = explode('=', $path);
if ($key =="c") {
$MyClass = $value;
continue;
}
if ($key =="m") {
$MyMethod = $value;
continue;
}

$_GET[$key] = $value;
}

// overloading is also ok, if PHP5.
if ($MyClass != "" && is_file($MyClass.".php")) {
include_once($MyClass.".php");
if (class_exists($MyClass)) {
$MyModel = new $MyClass;
if (method_exists($MyModel,"dispatch")) {
$MyModel->dispatch($MyMethod);
}
}
}


?>
-----user_proile.php

<?php
class user_proile
{
function dispatch($action)
{
echo $action;

}


}
?>

refer to:
2008/03/php-mvc-controller.html

2005/01/pathinfo.html

Thursday, March 27, 2008

PHP MVC controllerの勉強

class base {

function __construct() {
}
function dispatch($action){
try{
$this->$action();
}catch( Exception $e ){
$this->errorAction($e->getMessage());
}
}
function errorAction($str=null){
echo "overridden";
}
}

class Front extends Base {

function __construct() {
}

function page() {
throw new Exception( 'Template error.' );
echo "page";
}

function errorAction($str=null){
echo "Front:".$str;
}
}

$f = new Front;
$f->dispatch("page");

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;

---