简单实现一下php的MVC框架。
在服务器根目录下建立MVC文件夹,php-eclipse自动加入了PHP Language Library和PHP Include Path。
MVC文件夹内包含四个文件夹(或文件):controller文件夹,model文件夹,view文件夹,以及入口文件index.php。
1.对于controller文件夹,内有democontroller.php文件:
<?php
// class DemoController {
// public function index() {
// echo 'hello world';
// }
// }
// $dc = new DemoController();
// $dc -> index();
// controller/democontroller.php
class DemoController
{
// private $data = 'Hello furzoom!';
function index($param)
{
// echo 'hello world';
require(dirname ( __FILE__ ) . '/../view/index.php');
require(dirname ( __FILE__ ) . '/../model/model.php');
$model = new Model();
$view = new Index();
$data = $model->getData($param);
$view->display($data);
}
}// End of the class DemoController
// End of file democontroller.php
2.model文件夹内有model.php文件:
<?php
// model/model.php
class Model {
private $data = array(
'title' => 'Hello furzoom!',
'welcome' => 'Welcome to furzoom.com',
);
public function getData($key) {
return $this->data[$key];
}
}
// End of model.php
3.view文件夹内有index.php文件:
<?php
// view/index.php
class Index {
public function display($output) {
// ob_start();
echo $output;
// $a = 'index';
// echo $a;
}
}
// End of index.php
4.入口文件index.php:
<?php
// require (dirname ( __FILE__ ) . '/controller/democontroller.php');
// $controller = new DemoController ();
// $controller->index ();
//localhost/MVC/index.php?c=demo&a=index¶m=welcome
//index.php
// get runtime controller prefix
$c_str = $_GET['c'];
// the full name of controller
$c_name = $c_str.'controller';
// the path of controller
$c_path = 'controller/'.$c_name.'.php';
// get runtime action
$method = $_GET['a'];
// get runtime parameter
$param = $_GET['param'];
// load controller file
require($c_path);
// instantiate controller
$controller = new $c_name;
// run the controller method
$controller->$method($param);
// End of index.php
5.url是动态的,为localhost/MVC/index.php?c=demo&a=index¶m=welcome
内容就不具体介绍了,代码比较容易懂。