PHP框架開發之Route路由簡單實現

參數Laravel路由的使用方式,來效仿一個簡單的路由實現方式php

class Route
{
    /**
     * @var $_instance // 實例
     */
    private static $_instance = null;

    /**
     * @var $_currentPath // 當前URL中的地址
     */
    private $_currentPath = '';

    /**
     * @var $_prefix // URL地址中前綴
     */
    private $_prefix = '';

    private function __construct($currentPath)
    {
        $this->_currentPath = $currentPath;
    }

    // 經過靜態方法來進行Route路由實例化
    static function getInstance($currentPath)
    {
        if( is_null(self::$_instance) ){
            self::$_instance = new self($currentPath);
        }
        return self::$_instance;
    }

    /**
     * 實現GET請求的路由訪問
     *
     * @param string $path //訪問路由規則(路徑)
     * @param Closure $callback 匿名回調函數
     * 
     * @return Route
     */
    public function get($path,\Closure $callback)
    {
        if( !empty($this->_prefix) ){
            $path = '/'.$this->_prefix.$path;
        }
        if( $path == $this->_currentPath ){
            echo $callback();
            exit;
        }
        return $this;
    }

    /**
     * 實現路由前綴設定
     *
     * @param string $prefix //訪問路由前綴(路徑)
     * 
     * @return Route
     */
    public function prefix($prefix)
    {
        $this->_prefix = $prefix;
        return $this;
    }

    /**
     * 實現路由分組
     *
     * @param Closure $callback 路由組的具體實現
     * 
     * @return Route
     */
    public function group(\Closure $callback)
    {
        $callback($this);
        return $this;
    }

}

調用示例:函數

// 經過GET中s參數模擬路由規則的訪問
$currentPath = empty($_GET['s']) ? '/index/index' : $_GET['s'];


$route = Route::getInstance($currentPath);

// 實現流程:
// 1.判斷當前訪問的URL地址是否被設定
// 2.若是被設定則執行get方法中的$callback匿名函數
$route->get('/aaaa',function(){
    return 'Route Http Get Called';
});
$route->get('/bbbb',function(){
    return 'Route Http Get Called 2';
});

// 實現流程:
// 1.設定URL地址前綴:test
// 2.將路由前綴和get的路徑規則進行拼接
// 3.執行group方法中$callback匿名函數
// 4.判斷當前訪問的URL地址是否符合設定的路徑規則
// 5.若是被設定則執行get方法中的$callback匿名函數
$route->prefix('test')->group(function($route){
    $route->get('/aaaa',function(){
        return 'Route Group Http Get Called';
    });
});

以上只是個實現思路,歡迎互相探討交流!this

相關文章
相關標籤/搜索