一個簡單的php路由類
來源:易賢網(wǎng) 閱讀:778 次 日期:2016-08-18 15:19:49
溫馨提示:易賢網(wǎng)小編為您整理了“一個簡單的php路由類”,方便廣大網(wǎng)友查閱!

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

<?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("http://", "/", 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;

  }

}

希望本文所述對大家學習PHP程序設(shè)計有所幫助。

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:一個簡單的php路由類
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)