控制器類父類簡單的封裝了幾個跳轉的方法,`redirect()`。
~~~
<?php
//控制器父類
//判斷當前請求是否正常,如果不是通過index.php進行訪問的,就退出系統
if(!defined('ACCESS')) die('Hacking');
/**
* 控制器父類
*/
class Controller
{
/*
* 獲取到網址傳遞過來的參數,參數是以數組的形式存儲的
*/
public function __construct($argus)
{
$this->argus=$argus;
}
/*
* 跳轉方法
* 路徑 Login/index Api/Login/index
* 參數 name/huangfohai/age/20
*/
protected function redirect($route,$argu){
$argus=array();
if( strpos($route, "Admin")===0 || strpos($route,"Api")===0){//參數填寫方式:模塊/控制器/方法。 Api/Index/index
echo "這種跳轉方式暫時沒有寫。位置:app/Core/Controller.class.php 的redirect()";
}else{//參數填寫方式:/控制器/方法。 Index/index
//獲取控制器和方法
$request=explode("/", $route);
$controller=$request[0]."Controller";
$action=$request[1];
//獲取要傳遞的參數
if(!empty($argu)){
$res=explode("/", $argu);
for($i=0;$i<count($res);$i++){
if( $i % 2 ==0 ){
$argus[$res[$i]]=$res[$i+1];
}
}
}
$object=new $controller($argus);
$object->$action();
}
}
/*
* 傳遞參數
* @param string 鍵
* @param string 值
*/
protected function assign($name,$value){
$this->values[$name]=$value;
}
/*
* 加載模板的方法
*/
protected function display($template){
if(strpos($template, "Admin")===0 || strpos($template,"Api")===0){//參數填寫方式:模塊/控制器/方法。 Api/Index/index
echo "這種顯示模板的方式暫時沒有寫。位置:app/Core/Controller.class.php 的display()";
}else{//參數填寫方式:/控制器/方法。 Index/index
//獲取模板路徑
$vars=explode("/", $template);
if(MODULE == "Admin"){
$path=ADMIN_VIEW.$vars[0]."/".$vars[1].".html";
}else if(MODULE == "Api"){
$path=API_VIEW.$vars[0]."/".$vars[1].".html";
}
if(file_exists($path)){
$file=file_get_contents($path);
//循環替換掉模板里面的標簽
foreach ($this->values as $key => $value) {
$file=str_replace($key, $value, $file);
}
//要加入這句話,echo出來的html代碼才會被解析,不懂,因為回來的報文頭本身已經包含了它
//為什么還要設置
header('Content-Type:text/html; charset=utf-8');
echo $file;
exit;
}
}
}
}
?>
~~~