PHP에서 URL 라우팅 배포 기능을 구현하는 방법

coldplay.xixi
풀어 주다: 2023-03-05 13:18:01
원래의
2457명이 탐색했습니다.

PHP가 URL 경로 배포 기능을 구현하는 방법: 먼저 서버 구성에서 [/router/] 경로를 가로채고 경로 배포자를 구현하고 요청된 URI를 얻은 다음 마지막으로 모듈을 작성합니다.

PHP에서 URL 라우팅 배포 기능을 구현하는 방법

【관련 학습 권장사항: php 그래픽 튜토리얼

php에서 URL 라우팅 배포 기능을 구현하는 방법:

첫 번째 단계는 서버를 구성하는 것입니다. /router/ 경로/router/路径进行拦截

PHP에서 URL 라우팅 배포 기능을 구현하는 방법

 

调用某个文件夹目录下的index.php

PHP에서 URL 라우팅 배포 기능을 구현하는 방법

PHP에서 URL 라우팅 배포 기능을 구현하는 방법

특정 폴더 디렉터리의 index.php 페이지를 호출하세요. 이제 모든 모듈이 클래스 디렉터리의 별도 파일에 저장되어 있다고 가정합니다. 아래 그림과 같이 라우터와 동일한 레벨입니다.

두 번째 단계는 경로 분배기(index.php)를 구현하는 것입니다.

<!Doctype html>
 <html>
 <head>
 <title>路由测试~~</title>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 </head>
<body>
<?php
date_default_timezone_set("Asia/Shanghai");
 define("MODULE_DIR", "../class/");
 $_DocumentPath = $_SERVER[&#39;DOCUMENT_ROOT&#39;];
 $_FilePath = __FILE__;
 $_RequestUri = $_SERVER[&#39;REQUEST_URI&#39;]; 
 $_AppPath = str_replace($_DocumentPath, &#39;&#39;, $_FilePath);  //==>\router\index.php
 $_UrlPath = $_RequestUri;  //==>/router/hello/router/a/b/c/d/abc/index.html?id=3&url=http:
 $_AppPathArr = explode(DIRECTORY_SEPARATOR, $_AppPath);
 
 /**
 * http://192.168.0.33/router/hello/router/a/b/c/d/abc/index.html?id=3&url=http:
 * 
 * /hello/router/a/b/c/d/abc/index.html?id=3&url=http:
 */ 
 for ($i = 0; $i < count($_AppPathArr); $i++) {
   $p = $_AppPathArr[$i];
   if ($p) {
    $_UrlPath = preg_replace(&#39;/^\/&#39;.$p.&#39;\//&#39;, &#39;/&#39;, $_UrlPath, 1);
   }
 }
 
 $_UrlPath = preg_replace(&#39;/^\//&#39;, &#39;&#39;, $_UrlPath, 1);
 
 $_AppPathArr = explode("/", $_UrlPath);
 $_AppPathArr_Count = count($_AppPathArr);
 
 $arr_url = array(
  &#39;controller&#39; => &#39;index&#39;,
   &#39;method&#39; => &#39;index&#39;,
   &#39;parms&#39; => array()
 );
 
 $arr_url[&#39;controller&#39;] = $_AppPathArr[0];
 $arr_url[&#39;method&#39;] = $_AppPathArr[1];
 
 if ($_AppPathArr_Count > 2 and $_AppPathArr_Count % 2 != 0) {
   die(&#39;参数错误&#39;);
 } else {
   for ($i = 2; $i < $_AppPathArr_Count; $i += 2) {
     $arr_temp_hash = array(strtolower($_AppPathArr[$i])=>$_AppPathArr[$i + 1]);
     $arr_url[&#39;parms&#39;] = array_merge($arr_url[&#39;parms&#39;], $arr_temp_hash);
   }
 }
 
 $module_name = $arr_url[&#39;controller&#39;];
 $module_file = MODULE_DIR.$module_name.&#39;.class.php&#39;;
 $method_name = $arr_url[&#39;method&#39;];
 
 if (file_exists($module_file)) {
   include $module_file;
   
   $obj_module = new $module_name();
   
   if (!method_exists($obj_module, $method_name)) {
     die("要调用的方法不存在");
  } else {
     if (is_callable(array($obj_module, $method_name))) {
       $obj_module -> $method_name($module_name, $arr_url[&#39;parms&#39;]);
       
       $obj_module -> printResult();
     }
   }
   
 } else {
   die("定义的模块不存在");
 }
  
 ?>
 
</body>
 </html>
로그인 후 복사

요청한 URI를 가져온 다음 로드할 모듈 이름을 가져옵니다. 그리고 호출 메소드 이름은 uri 매개변수로 간단하게 판단하세요..


세 번째 단계는 모듈을 작성하는 것입니다

위 uri에 따르면 우리가 호출하려는 것은 Hello 모듈 아래의 라우터 메소드이고, 그런 다음 Hello.class.php 파일이라는 파일을 정의할 수 있습니다(Linux에서는 대소문자를 구분합니다)

<?php
class Hello {
 private $_name;
private $_varValue;
   
   function __construct() {
     
   }
   
   function router() {
     $this->_name = func_get_arg(0);
     $this->_varValue = func_get_arg(1);
   }   
   function printResult() {
    echo $this->_name;
    echo "<p>";
    echo var_dump($this->_varValue);
     echo "</p>";
  }
 }
 ?>
로그인 후 복사

마찬가지로 Ha 모듈을 작성할 수 있습니다...

이것은 매우 간단한 것을 구현한 것으로 간주될 수 있습니다. URL 라우팅 배포 기능...

관련 학습 추천: 🎜php 프로그래밍🎜(동영상)🎜🎜🎜

위 내용은 PHP에서 URL 라우팅 배포 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!