html5中文学习网

您的位置: 首页 > 网络编程 > PHP编程 » 正文

PHP实例:实现超级简单的MVC结构_PHP教程_编程技术

[ ] 已经帮助:人解决问题
下面是一个超级简单的MVC结构实现,甚至连数据源都用了一个内置的固定数组,虽然简单,但其实众多的PHP Framework核心实现的思想应该和这个是差不多的

只不过一些framework提供了更多的方便开发者使用的工具,我也想自己来实现一个PHP的 框架,目前正在着手策划中,也希望自己能够从框架的开发中学习到更多的PHP设计思想和方法。rUPHTML5中文学习网 - HTML5先行者学习网

Controller.phprUPHTML5中文学习网 - HTML5先行者学习网

include 'Model.php';
include 'View.php';rUPHTML5中文学习网 - HTML5先行者学习网

class Controller {
    private $model     = '';
    private $view     = '';
   
    public function Controller(){
        $this->model    =    new Model();
        $this->view        =    new View();
    }
   
    public function doAction( $method = 'defaultMethod', $params = array() ){
        if( empty($method) ){
            $this->defaultMethod();
        }else if( method_exists($this, $method) ){
            call_user_func(array($this, $method), $params);
        }else{
            $this->nonexisting_method();
        }
    }
   
    public function link_page($name = ''){
        $links = $this->model->getLinks();
        $this->view->display($links);
       
        $result = $this->model->getResult($name);
        $this->view->display($result);
    }
   
    public function defaultMethod(){
        $this->br();
        echo "This is the default method. ";
    }
   
    public function nonexisting_method(){
        $this->br();
        echo "This is the noexisting method. ";
    }
   
    public function br(){
        echo "<br />";
    }
}rUPHTML5中文学习网 - HTML5先行者学习网


$controller = new Controller();
$controller->doAction('link_page', 'b');
$controller->doAction();rUPHTML5中文学习网 - HTML5先行者学习网


Model.phprUPHTML5中文学习网 - HTML5先行者学习网


Code
class Model {
    private $database = array(
        "a"    =>    "hello world",
        "b"    =>    "ok well done",
        "c"    =>    "good bye",
    );
   
    //@TODO connect the database
   
    //run the query and get the result
    public function getResult($name){
        if( empty($name) ){
            return FALSE;
        }
       
        if( in_array($name, array_keys( $this->database ) ) ){
            return $this->database[$name];
        }
    }rUPHTML5中文学习网 - HTML5先行者学习网

    public function getLinks(){
        $links = "<a href='#'>Link A</a>  ";
        $links.= "<a href='#'>Link B</a>  ";
        $links.= "<a href='#'>Link C</a>  ";
       
        return $links;
    }
}rUPHTML5中文学习网 - HTML5先行者学习网

View.phprUPHTML5中文学习网 - HTML5先行者学习网


class View {
   
    public function display($output){
//        ob_start();
       
        echo $output;
    }
   
}rUPHTML5中文学习网 - HTML5先行者学习网

rUPHTML5中文学习网 - HTML5先行者学习网
rUPHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助