How to implement simple routing in PHP? This article mainly introduces a simple PHP routing class in detail. Interested friends can refer to it. I hope to be helpful.
The example of this article shares with you a simple routing class written in PHP for your reference. The specific content is as follows
<?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; } }
Related recommendations:
thinkphp Ultimate Detailed Explanation of Routing Rules (With Pseudo-static) - A must-read for noobs
Detailed explanation of Yii operating mechanism and routing
The way to learn MVC framework in PHP
The above is the detailed content of How to implement simple routing in PHP. For more information, please follow other related articles on the PHP Chinese website!