<?php class DemoController { function index() { echo('hello world'); } } /* End of file democontroller.php */
这个文件里面咱们只是创建了一个名为DemoController的对象并包含一个index的方法,该方法输出hello world。下面在index.php中执行DemoController中index方法。
index.php的代码以下 php
<?php require('controller/democontroller.php'); $controller=new DemoController(); $controller->index(); /* End of file index.php */
运行index.php,ok如愿咱们看到了咱们久违的hello world。这两个文件很是简单,但也揭示了一点点mvc的本质,经过惟一入口运行咱们要运行的控制器。固然controller部分应该是由uri来决定的,那么咱们来改写一下index.php使他能经过uri来决定运行那个controller。
index.php改写代码以下: html
<?php $c_str=$_GET['c']; //获取要运行的controller $c_name=$c_str.'Controller'; //按照约定url中获取的controller名字不包含Controller,此处补齐。 $c_path='controller/'.$c_name.'.php'; //按照约定controller文件要创建在controller文件夹下,类名要与文件名相同,且文件名要所有小写。 $method=$_GET['a']; //获取要运行的action require($c_path); //加载controller文件 $controller=new $c_name; //实例化controller文件 $controller->$method(); //运行该实例下的action /* End of file index.php */
在浏览器中输入http://localhost/index.php?c=demo&a=index,获得了咱们的hello world。固然若是咱们有其余的controller而且要运行它,只要修改url参数中的c和a的值就能够了。
这里有几个问题要说明一下。
1、php是动态语言,咱们直接能够经过字符串new出咱们想要的对象和运行咱们想要的方法,即上面的new $c_name,咱们能够理解成new 'DemoController',由于$c_name自己的值就是'DemoController',固然直接new 'DemoController'这么写是不行的,其中的'DemoController'字符串必须经过一个变量来中转一下。方法也是同样的。
2、咱们在url中c的值是demo,也就是说$c_name 的值应该是demoController呀,php不是区分大小写吗,这样也能运行吗?php区分大小写这句话不完整,在php中只有变量(前面带$的)和常量(define定义的)是区分大小写的,而类名方,法名甚至一些关键字都是不区分大小写的。而true,false,null等只能所有大写或所有小写。固然咱们最好在实际编码过程当中区分大小写。
3、视图
咱们在前面的controller中只是输出了一个“hello world”,并无达到mvc的效果,下面我将在此基础上增长视图功能,相信到这里你们基本已经能想到如何添加视图功能了。对,就是经过万恶的require或者include来实现。
首先咱们在view文件夹下创建一个index.php,随便写点什么(呵呵,我写的仍是hello world)。以后咱们改写一下咱们以前的DemoController。代码以下: 浏览器
<?php class DemoController { function index() { require('view/index.php'); } } /* End of file democontroller.php */
再在浏览器中运行一下,看看是否是已经输出了咱们想要的内容了。
接着咱们经过controller向view传递一些数据看看,代码以下: mvc
<?php class DemoController { function index() { $data['title']='First Title'; $data['list']=array('A','B','C','D'); require('view/index.php'); } } /* End of file democontroller.php */
view文件夹下index.php文件代码以下: 框架
<html> <head> <title>demo</title> </head> <body> <h1><?php echo $data['title'];?></h1> <?php foreach ($data['list'] as $item) { echo $item.'<br>'; } ?> </body> </html>
最后 MVC就是 Model View Controller 模型 视图 控制器 post