如何用PHP实现自己的MVC
答案:2 悬赏:50 手机版
解决时间 2021-12-04 02:43
- 提问者网友:爱了却不能说
- 2021-12-03 14:32
如何用PHP实现自己的MVC
最佳答案
- 五星知识达人网友:何以畏孤独
- 2021-12-03 15:17
MVC三个字母的含义: M:Model 模型,负责数据库操作。 V:View 视图,负责调用Model调取数据,再调用模板,展示出最终效果。 C:Controller 控制器,程序的入口,决定改调用哪个View,并告诉View该做什么。 下面是一个超级简单的MVC结构实现: Controller.php include 'Model.php'; include 'View.php'; 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 ""; } } $controller = new Controller(); $controller->doAction('link_page', 'b'); $controller->doAction(); Model.php 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]; } } public function getLinks(){ $links = "Link A "; $links.= "Link B "; $links.= "Link C "; return $links; } } View.php class View { public function display($output){ // ob_start(); echo $output; }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯