使用自动加载和解析url的参数,实现调用到不同的控制器,实现了pathinfo模式和普通的url模式
文件结构:
|--controller
|--index
|--index.php
|--application.php
application.php
<?php
class application{
public static function main(){
header("content-type:text/html;charset=utf-8");
self::register();
self::router();
}
public static function register(){
spl_autoload_register("self::loadclass");
}
public static function loadclass($class){
$class=str_replace('\', '/', $class);
$class="./".$class.".php";
require_once $class;
}
public static function router(){
if(isset($_server['path_info'])){
$pathinfo=array_filter(explode("/", $_server['path_info']));
for($i=1;$i<=count($pathinfo);$i++){
$key=isset($pathinfo[$i]) ? $pathinfo[$i] : '';
$value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";
switch ($i) {
case 1:
$_get['m']=ucfirst($key);
break;
case 2:
$_get['c']=ucfirst($key);
break;
case 3:
$_get['a']=$key;
break;
default:
if($i>3){
if($i%2==0){
$_get[$key]=$value;
}
}
break;
}
}
}
$_get['m']=!empty($_get['m']) ? ucfirst($_get['m']) : 'index';
$_get['c']=!empty($_get['c']) ? ucfirst($_get['c']) : 'index';
$_get['a']=!empty($_get['a']) ? $_get['a'] : 'index';
$class="\controller\{$_get['m']}\{$_get['c']}";
$controller=new $class;
$controller->$_get['a']();
}
}
application::main();
controllerindexindex.php
<?php
namespace controllerindex;
use serviceuser;
class index{
public function __construct(){
echo "构造方法<br/>";
}
public function index(){
new user();
print_r($_get);
}
public function login(){
echo "login()";
}
}
效果:
以上这篇php url的pathinfo模式加载不同控制器的简单实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持硕编程。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!