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

The pathinfo mode of url loads the implementation of different controllers

PHP中文网
Release: 2017-06-02 13:55:06
Original
2174 people have browsed it

使用自动加载和解析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();
Copy after login

\Controller\Index\Index.php

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

效果:



Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template