Home  >  Article  >  php教程  >  The pathinfo mode of url loads the implementation of different controllers

The pathinfo mode of url loads the implementation of different controllers

PHP中文网
PHP中文网Original
2017-06-02 13:55:062114browse

使用自动加载和解析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()"

效果:



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn