Rumah  >  Artikel  >  php教程  >  url的pathinfo模式加载不同控制器的实现

url的pathinfo模式加载不同控制器的实现

PHP中文网
PHP中文网asal
2017-06-02 13:55:062116semak imbas

使用自动加载和解析url的参数,实现调用到不同的控制器,实现了pathinfo模式和普通的url模式

文件结构:

|--Controller
  |--Index
    |--Index.php

|--Application.php

Application.php

<?
phpclass 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(&#39;\\&#39;, &#39;/&#39;, $class);$class="./".$class.".php";require_once $class;        
    }public static function router(){if(isset($_SERVER[&#39;PATH_INFO&#39;])){$pathinfo=array_filter(explode("/", $_SERVER[&#39;PATH_INFO&#39;]));for($i=1;$i<=count($pathinfo);$i++){$key=isset($pathinfo[$i]) ? $pathinfo[$i] : &#39;&#39;;$value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";switch ($i) {case 1:$_GET[&#39;m&#39;]=ucfirst($key);break;case 2:$_GET[&#39;c&#39;]=ucfirst($key);break;case 3:$_GET[&#39;a&#39;]=$key;break;default:if($i>3){if($i%2==0){$_GET[$key]=$value;
                            }
                        }break;
                }
            }
        }$_GET[&#39;m&#39;]=!empty($_GET[&#39;m&#39;]) ? ucfirst($_GET[&#39;m&#39;]) : &#39;Index&#39;;$_GET[&#39;c&#39;]=!empty($_GET[&#39;c&#39;]) ? ucfirst($_GET[&#39;c&#39;]) : &#39;Index&#39;;$_GET[&#39;a&#39;]=!empty($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : &#39;index&#39;;$class="\\Controller\\{$_GET[&#39;m&#39;]}\\{$_GET[&#39;c&#39;]}";$controller=new $class;$controller->$_GET[&#39;a&#39;]();
    }
}

Application::main();

\Controller\Index\Index.php

<?  "构造方法
" (  "login()"

效果:



Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn