首頁  >  文章  >  後端開發  >  PHP如何實作簡單路由

PHP如何實作簡單路由

*文
*文原創
2018-01-02 11:09:026791瀏覽

PHP如何實作簡單路由?本文主要為大家詳細介紹了一個簡單的php路由類,有興趣的朋友可以參考一下。希望對大家有幫助。

本文實例為大家分享了php編寫一個簡單的路由類,供大家參考,具體內容如下

<?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[&#39;PHP_SELF&#39;]) . &#39;/&#39; . $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[&#39;REQUEST_URI&#39;], PHP_URL_PATH);
    $requestMethod = $_SERVER[&#39;REQUEST_METHOD&#39;];
 
    if (strpos(self::$match, &#39;(&#39;) === false) {
      self::normalMatch($requestUri);
    } else {
      self::regexpMatch($requestUri);
    }
 
  }
 
  /**
   * Determining whether the route is found
   * @return boolean
   */
  public static function isNotFound()
  {
    return !self::$routeFound;
  }
 
}

相關推薦:

thinkphp 路由規則終極詳解(附偽靜態)-菜鳥必看

Yii運作機制及路由詳解

#PHP學習MVC框架之路由

#

以上是PHP如何實作簡單路由的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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