一个简单的php路由类

2025-05-29 0 105

本文实例为大家分享了php编写一个简单的路由类,供大家参考,具体内容如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95
<?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;

}

}

下载地址:https://github.com/cmhc/Hcrail

希望本文所述对大家学习PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 一个简单的php路由类 https://www.kuaiidc.com/97592.html

相关文章

发表评论
暂无评论