首頁 php教程 PHP源码 一个简单的路由类

一个简单的路由类

Jun 02, 2016 am 09:14 AM

跳至 [1] [全屏预览]
<?php
namespace cmhc\Hcrail;

class Hcrail
{

    /**
     * callback function
     * @var callable
     */
    protected static $callback;

    /**
     * match string or match regexp
     * @var string
     */
    protected static $match;

    protected static $routeFound = false;

    /**
     * deal with get,post,head,put,delete,options,head
     * @param   $method
     * @param   $arguments
     * @return
     */
    public static function __callstatic($method, $arguments)
    {
        self::$match = str_replace("//", "/", dirname($_SERVER['PHP_SELF']) . '/' . $arguments[0]);
        self::$callback = $arguments[1];
        self::dispatch();
        return;
    }

    /**
     * processing ordinary route matches
     * @param  string $requestUri
     * @return
     */
    public static function normalMatch($requestUri)
    {
        if (self::$match == $requestUri) {
            self::$routeFound = true;
            call_user_func(self::$callback);
        }
        return;
    }

    /**
     * processing regular route matches
     * @param  string $requestUri
     * @return
     */
    public static function regexpMatch($requestUri)
    {
        //处理正则表达式
        $regexp = self::$match;
        preg_match("#$regexp#", $requestUri, $matches);
        if (!empty($matches)) {
            self::$routeFound = true;
            call_user_func(self::$callback, $matches);
        }
        return;
    }

    /**
     * dispatch route
     * @return
     */
    public static function dispatch()
    {
        if (self::$routeFound) {
            return ;
        }
        $requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $requestMethod = $_SERVER['REQUEST_METHOD'];

        if (strpos(self::$match, '(') === false) {
            self::normalMatch($requestUri);
        } else {
            self::regexpMatch($requestUri);
        }

    }

    /**
     * Determining whether the route is found
     * @return boolean
     */
    public static function isNotFound()
    {
        return !self::$routeFound;
    }

}
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)