[PHP] url的pathinfo模式載入不同控制器的實現

來源:互聯網
上載者:User

標籤:

使用自動載入和解析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(‘\\‘, ‘/‘, $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();

\Controller\Index\Index.php

<?phpnamespace Controller\Index;use Service\User;class Index{    public function __construct(){        echo "構造方法<br/>";    }    public function index(){        new User();        print_r($_GET);    }    public function login(){        echo "login()";    }}

效果:

[PHP] url的pathinfo模式載入不同控制器的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.