Routing的作用:它首先是获取到View传过来的请求,并解析Url请求中Controller和Action以及数据,其次他将识别出来的数据传递给Controller的Action(Controller的方法)。这是Routing组件的两个重要的作用!
接下来我给大家说下怎么制作路由
1:首先,先在根目录下建一个.htaccess的文件,里面写入:
<IfModule mod_rewrite.c >
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}!-F
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
这个文件的作用就是当url的过来的时候,我门把他映射到index.php里面
2:结下来,我门建一个文件,命名route.php文件,写入:
<?php
namespace core\lib;
use core\lib\conf;
class route{
public function __construct()
{
/*
* xxx.com/index/index
* xxx.com/index.php/index/index
*1:隐藏index.php
* 2:获取URL 参数部分
* 3:返回对应控制和方法
*/
if(isset($_SERVER['REQUEST_URI'])&&$_SERVER['REQUEST_URI'] != '/'){
$path=$_SERVER['REQUEST_URI']='/index/index';
$patharr=explode('/',trim($path,'/'));
if(isset($patharr)){
$this->ctr=$patharr[0];
}
unset($patharr[0]);
if(isset($patharr[1])){
$this->action=$patharr[1];
unset($patharr[1]);
}else{
$this->action=conf::get('ACTION','route');
}
//URL多余部分转换成GET
//id/1/str/2/test/3
$count=count($patharr)+2;
$i=0+2;
while($i<$count){
if(isset($patharr[$i+1])){
<pre name="code" class="php"> $_GET[$patharr[$i]]=$patharr[$i+1];
}else{
$i=$i+2;
} } }else{ $this->ctr=conf::get('CTR','route'); $this->action=conf::get('ACTION','route'); } }}
这样,我们的路由就完成了
我们说下怎么建控制器
控制器:相信大家都了解了,我废话不多说,直接开始吧!
1:首先,我门新建一个控制器的文件夹,命名为indexCtr.php文件把里面写上
<?php
namespace app\ctr;
use core\lib\model;
header('content-type:text/html;charset=utf8');
class indexCtr extends \core\coom{
public function index(){
echo "hello world";
}
}
2:我门在刚开始定义的那个自动加载类里面的run这个方法里面加上这个:
//加载控制器
$ber=new \core\lib\route();
$strlClass=$ber->ctr;
$action=$ber->action;
$strfile=str_replace('\\','/',APP.'/ctr/'.$strlClass.'Ctr.php');
$cltrlClass='\\'.MODULE.'\ctr\\'.$strlClass.'Ctr';
// echo $strfile;die;
if(is_file($strfile)){
include $strfile;
$ctr=new $cltrlClass();
$ctr->index();
}
//这里面的那个MODULE,是在跟目录下的那个index.php里面的那个自定义的,我门刚开始也说了
模型类这个简单
1:我门建一个文件夹名字是model.php
<?php
namespace core\lib;
use core\lib\conf;
class model extends \medoo{
public function __construct()
{
$dsn='mysql:host=localhost;dbname=表明';
$username="root";
$password="root";
try{
parent::__construct($dsn,$username,$pwssword);
}catch(\PDOException $e){
p($e->getMessage());
}
}
这个就写完了,接下来我门在控制器里面写
1:实例化这个类
2:写个sql语句
3:执行下这个sql语句,就哦了!!!
接下类我说下这个视图
1:在控制器里面写下
$data="asdf";
$this->assign('data',$data);
$this->display('index.html');
2:在自动加载类里面写上这两个方法
public function assign($name,$value){
$this->assign[$name]=$value;
}
public function display($file){
$file=APP.'/view/'.$file;
if(is_file($file)){
\Twig_Autoloader::register();
$loader = new \Twig_Loader_Filesystem(APP.'/view');
$twig = new \Twig_Environment($loader, array(
'cache' =>IMOOC.'/log/twig',
'debug'=>BEBUG,
));
$template = $twig->loadTemplate('index.html');
$template->display($this->assign?$this->assign:'');
}
}
好了!这就完成了!如果大家有什么问题的话可以在下面留言;