search
HomeBackend DevelopmentPHP TutorialHow to implement route mapping to specified controller in PHP

How to implement route mapping to specified controller in PHP

Jun 01, 2018 pm 03:25 PM
phpdesignationcontroller

这篇文章主要为大家详细介绍了PHP实现路由映射到指定控制器的相关资料,感兴趣的小伙伴们可以参考一下

自定义路由的功能,指定到pathinfo的url上,再次升级之前的脚本 

SimpleLoader.php

<?php
class SimpleLoader{
 public static function run($rules=array()){
 header("content-type:text/html;charset=utf-8");
 self::register();
 self::commandLine();
 self::router($rules);
 self::pathInfo();
 }
 //自动加载
 public static function loadClass($class){
 $class=str_replace(&#39;\\&#39;, &#39;/&#39;, $class);
 $dir=str_replace(&#39;\\&#39;, &#39;/&#39;, __DIR__);
 $class=$dir."/".$class.".php";
 if(!file_exists($class)){
  header("HTTP/1.1 404 Not Found");
 }
 require_once $class; 
 }
 //命令行模式
 public static function commandLine(){
 if(php_sapi_name()=="cli"){
  $_SERVER[&#39;PATH_INFO&#39;]="";
  foreach ($_SERVER[&#39;argv&#39;] as $k=>$v) {
  if($k==0) continue;
  $_SERVER[&#39;PATH_INFO&#39;].="/".$v;
  }
 }
 }
 //路由模式
 public static function router($rules){
 if(isset($_SERVER[&#39;PATH_INFO&#39;]) && !empty($rules)){
  $pathInfo=ltrim($_SERVER[&#39;PATH_INFO&#39;],"/");
  foreach ($rules as $k=>$v) {
  $reg="/".$k."/i";
  if(preg_match($reg,$pathInfo)){
   $res=preg_replace($reg,$v,$pathInfo);
   $_SERVER[&#39;PATH_INFO&#39;]=&#39;/&#39;.$res;
  }
  }
 }
 }
 //pathinfo处理
 public static function pathInfo(){
 if(isset($_SERVER[&#39;PATH_INFO&#39;])){
  $pathinfo=array_filter(explode("/", $_SERVER[&#39;PATH_INFO&#39;]));
  for($i=1;$i<=count($pathinfo);$i++){
  $key=isset($pathinfo[$i]) ? $pathinfo[$i] : &#39;&#39;;
  $value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";
  switch ($i) {
   case 1:
   $_GET[&#39;m&#39;]=ucfirst($key);
   break;
   case 2:
   $_GET[&#39;c&#39;]=ucfirst($key);
   break;
   case 3:
   $_GET[&#39;a&#39;]=$key;
   break;
   default:
   if($i>3){
    if($i%2==0){
    $_GET[$key]=$value;
    }
   }
   break;
  }
  }
 }
 $_GET[&#39;m&#39;]=!empty($_GET[&#39;m&#39;]) ? ucfirst($_GET[&#39;m&#39;]) : &#39;Index&#39;;
 $_GET[&#39;c&#39;]=!empty($_GET[&#39;c&#39;]) ? ucfirst($_GET[&#39;c&#39;]) : &#39;Index&#39;;
 $_GET[&#39;a&#39;]=!empty($_GET[&#39;a&#39;]) ? $_GET[&#39;a&#39;] : &#39;index&#39;;
 $class="\\Controller\\{$_GET[&#39;m&#39;]}\\{$_GET[&#39;c&#39;]}";
 $controller=new $class;
 if(method_exists($controller, $_GET[&#39;a&#39;])){
  $controller=new $class;
  $controller->$_GET[&#39;a&#39;]();
 }else{
  header("HTTP/1.1 404 Not Found");
  echo "404";
 }
 }
 //致命错误回调
 public static function shutdownCallback(){
 $e=error_get_last();
 if(!$e) return;
 self::myErrorHandler($e[&#39;type&#39;],&#39;<font color="red">Fatal Error</font> &#39;.$e[&#39;message&#39;],$e[&#39;file&#39;],$e[&#39;line&#39;]);
 }
 //错误处理
 protected static function myErrorHandler($errno,$errstr,$errfile,$errline){
 list($micseconds,$seconds)=explode(" ",microtime());
 $micseconds=round($micseconds*1000);
 $micseconds=strlen($micseconds)==1 ? &#39;0&#39;.$micseconds : $micseconds;
 if(php_sapi_name()=="cli"){
  $break="\r\n";
 }else{
  $break="<br/>";
 }
 $mes="[".date("Y-m-d H:i:s",$seconds).":{$micseconds}] ".$errfile." ".$errline." line ".$errstr.$break;
 echo $mes; 
 }
 //注册
 public static function register(){
 error_reporting(0);
 set_error_handler(function($errno,$errstr,$errfile,$errline){
  self::myErrorHandler($errno,$errstr,$errfile,$errline);
 });
 register_shutdown_function(function(){
  self::shutdownCallback();
 });
 spl_autoload_register("self::loadClass");
 }
}

如何使用
index.php 

<?php
//路由映射
$rules=array(
 &#39;^user$&#39;=>&#39;User/User/getUserList&#39;,
 &#39;^user\/(\d+)$&#39;=>&#39;User/User/getUserById/id/$1&#39;,
 &#39;^user\/(\d+)\/article$&#39;=>&#39;User/User/getUserArticle/uid/$1&#39;
);
require_once "SimpleLoader.php";
SimpleLoader::run($rules);

 

控制器啥样
\Controller\User\User.php

<?php
namespace Controller\User;

class User{
 public function getUserById(){
 echo "用户信息id {$_GET[&#39;id&#39;]} 的信息";
 }
 public function getUserList(){
 echo "用户列表";
 }
 public function getUserArticle(){
 echo "用户id {$_GET[&#39;uid&#39;]} 的文章列表";
 }
}

效果呢:

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP实现多图上传结合uploadify插件思路分析

thinkPHP自定义类实现方法详解

PHP实现的同步推荐操作API接口案例详解

The above is the detailed content of How to implement route mapping to specified controller in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.