php映射,PHP实现路由映射到指定控制器

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

SimpleLoader.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('\\', '/', $class);

$dir=str_replace('\\', '/', __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['PATH_INFO']="";

foreach ($_SERVER['argv'] as $k=>$v) {

if($k==0) continue;

$_SERVER['PATH_INFO'].="/".$v;

}

}

}

//路由模式

public static function router($rules){

if(isset($_SERVER['PATH_INFO']) && !empty($rules)){

$pathInfo=ltrim($_SERVER['PATH_INFO'],"/");

foreach ($rules as $k=>$v) {

$reg="/".$k."/i";

if(preg_match($reg,$pathInfo)){

$res=preg_replace($reg,$v,$pathInfo);

$_SERVER['PATH_INFO']='/'.$res;

}

}

}

}

//pathinfo处理

public static function pathInfo(){

if(isset($_SERVER['PATH_INFO'])){

$pathinfo=array_filter(explode("/", $_SERVER['PATH_INFO']));

for($i=1;$i<=count($pathinfo);$i++){

$key=isset($pathinfo[$i]) ? $pathinfo[$i] : '';

$value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";

switch ($i) {

case 1:

$_GET['m']=ucfirst($key);

break;

case 2:

$_GET['c']=ucfirst($key);

break;

case 3:

$_GET['a']=$key;

break;

default:

if($i>3){

if($i%2==0){

$_GET[$key]=$value;

}

}

break;

}

}

}

$_GET['m']=!empty($_GET['m']) ? ucfirst($_GET['m']) : 'Index';

$_GET['c']=!empty($_GET['c']) ? ucfirst($_GET['c']) : 'Index';

$_GET['a']=!empty($_GET['a']) ? $_GET['a'] : 'index';

$class="\\Controller\\{$_GET['m']}\\{$_GET['c']}";

$controller=new $class;

if(method_exists($controller, $_GET['a'])){

$controller=new $class;

$controller->$_GET['a']();

}else{

header("HTTP/1.1 404 Not Found");

echo "404";

}

}

//致命错误回调

public static function shutdownCallback(){

$e=error_get_last();

if(!$e) return;

self::myErrorHandler($e['type'],'Fatal Error '.$e['message'],$e['file'],$e['line']);

}

//错误处理

protected static function myErrorHandler($errno,$errstr,$errfile,$errline){

list($micseconds,$seconds)=explode(" ",microtime());

$micseconds=round($micseconds*1000);

$micseconds=strlen($micseconds)==1 ? '0'.$micseconds : $micseconds;

if(php_sapi_name()=="cli"){

$break="\r\n";

}else{

$break="
";

}

$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

//路由映射

$rules=array(

'^user$'=>'User/User/getUserList',

'^user\/(\d+)$'=>'User/User/getUserById/id/$1',

'^user\/(\d+)\/article$'=>'User/User/getUserArticle/uid/$1'

);

require_once "SimpleLoader.php";

SimpleLoader::run($rules);

控制器啥样

\Controller\User\User.php

namespace Controller\User;

class User{

public function getUserById(){

echo "用户信息id {$_GET['id']} 的信息";

}

public function getUserList(){

echo "用户列表";

}

public function getUserArticle(){

echo "用户id {$_GET['uid']} 的文章列表";

}

}

效果呢:

829f282b77b610b1b6fdcdfb74ed006e.png

4da7b2c7a370230292a0a012f4f6e3e6.png

59d548a17d7ab7d494273c0d56b190e6.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541391.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

stl vector 函数_vector :: clear()函数,以及C ++ STL中的示例

stl vector 函数C vector :: clear()函数 (C vector::clear() function) vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the 0 sized vector after removing all elements. vector …

Commonjs规范及Node模块实现

前面的话 Node在实现中并非完全按照CommonJS规范实现&#xff0c;而是对模块规范进行了一定的取舍&#xff0c;同时也增加了少许自身需要的特性。本文将详细介绍NodeJS的模块实现 引入 nodejs是区别于javascript的&#xff0c;在javascript中的顶层对象是window&#xff0c;而在…

thinkphp3 php jwt,ThinkPHP5 使用 JWT 进行加密

- 使用 Composer安装此扩展- 代码示例<?php /*** [InterCommon-接口公用]* Author RainCyan* DateTime 2019-08-12T16:38:080800*/namespace app\hladmin\controller;use think\Controller;use \Firebase\JWT\JWT;class InterCommonController extends Controller {private…

数据管理与商业智能_商业智能与数据科学

数据管理与商业智能In this heavily jargonized trade, the words typically overlap one another, leading to a scarcity of understanding or a state of confusion around these ideas. whereas big data vs analytics or computing vs machine learning vs cognitive inte…

JavaWeb网上图书商城完整项目--day02-14.登录功能的login页面处理

1、现在注册成功之后&#xff0c;我们来到登录页面&#xff0c;登录页面在于 在登录页面。我们也需要向注册页面一样对登录的用户名、密码 验证码等在jsp页面中进行校验&#xff0c;校验我们单独放置一个login.js文件中进行处理&#xff0c;然后login.jsp加载该js文件 我们来看…

php多线程是什么意思,多线程是什么意思

线程是操作系统能够进行运算调度的最小单位&#xff0c;它被包含在进程之中&#xff0c;是进程中的实际运作单位&#xff0c;而多线程就是指从软件或者硬件上实现多个线程并发执行的技术&#xff0c;具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程&#…

c++一个类创建多个对象_C ++ | 创建一个类的多个对象

c一个类创建多个对象In the below program, we are creating a C program to create multiple objects of a class. 在下面的程序中&#xff0c;我们正在创建一个C 程序来创建一个类的多个对象 。 /* C program to create multiple objects of a class */#include <iostrea…

Activity中与ListActivity中使用listview区别

一.Activity中与ListActivity中使用listview区别&#xff08;本身没多大区别&#xff0c;只是ListActivity在listview的显示上做了一些优化&#xff09;Activity中使用Listview步骤&#xff1a;1.xml布局中,ListView标签id可以任意取值如&#xff1a;<ListView andro…

java相关是什么,什么是java

java基础常见面试题&#xff0c;这是一篇超长的随笔&#xff01;&#xff01;&#xff01;1. Java基础部分....................................................... 4 1、一个".java"源文件中是否可以包括多个类(不是内部类)&#xff1f;有什么限制&#xff1f;.. …

如何在Scala中将Double转换为String?

Double in Scala is a data type that stores numerical values that have decimals. It can store a 64-bit floating point number. Scala中的Double是一种数据类型&#xff0c;用于存储带有小数的数值。 它可以存储一个64位浮点数。 Example: 例&#xff1a; val decimal…

basic knowledge

Position 属性&#xff1a;规定元素的定位类型。即元素脱离文档流的布局&#xff0c;在页面的任意位置显示。 ①absolute &#xff1a;绝对定位&#xff1b;脱离文档流的布局&#xff0c;遗留下来的空间由后面的元素填充。定位的起始位置为最近的父元素(postion不为static)&…

avatar.php uid,phpcms函数库中获取会员头像方法get_memberavatar()有时无效问题

修复方法&#xff1a;首先我先给出无效情况的演示代码&#xff0c;如下&#xff1a;$userid intval($_GET[userid]);$userinfo $this->db->get_one(userid.$userid);$this->db->set_model(10); //原因便在这里$userdetail $this->db->get_one("useri…

ruby 集合 分组_将Ruby中两个集合的所有元素结合在一起

ruby 集合 分组In this program, we will see how we can combine the two sets? This is not a very difficult task. This can be easily done with the help of the operator. In many places of programming, you will find that operator is overloaded for various ty…

​Python中面向对象的编程

Python面向对象的编程1概述&#xff08;1&#xff09;面向对象编程面向对象的编程是利用“类”和“对象”来创建各种模型来实现对真实世界的描述&#xff0c;使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单&#xff0c;并且可以大大提高程序开发效率&a…

php中用for循环制作矩形,PHP中for循环语句的几种变型

PHP中for循环语句的几种变型2021-01-22 10:21:42406for语句可以说是PHP(同时也是多种语言)的循环控制部份最基本的一个语句了&#xff0c;for语句的执行规律和基础用法在这里就不多说&#xff0c;可以参见PHP手册for语句部分。PHP手册中对它的语法定义如下&#xff1a;for(expr…

c语言用命令行编译运行程序_使用C程序执行系统命令

c语言用命令行编译运行程序Sometimes, we may need to execute Linux/Windows DOS commands through our C program. (Note: the code given below is compiled and executed on Linux GCC compiler, so here we are testing Linux commands only). 有时&#xff0c;我们可能需…

python 熊猫,Python熊猫

我试图连续分组和计算相同的信息&#xff1a;#Functionsdef postal_saude ():global df, lista_solic#List of solicitantes in Postal Saudelist_sol [lista_solic["name1"], lista_solic["name2"]]#filter Postal Saude Solicitantesdf df[(df[Cliente…

Spring的两种任务调度Scheduled和Async

Spring提供了两种后台任务的方法,分别是: 调度任务&#xff0c;Schedule异步任务&#xff0c;Async当然&#xff0c;使用这两个是有条件的&#xff0c;需要在spring应用的上下文中声明<task:annotation-driven/>当然&#xff0c;如果我们是基于java配置的&#xff0c;需要…

建立单链表 单链表的插入_单链列表插入

建立单链表 单链表的插入All possible cases: 所有可能的情况&#xff1a; Inserting at beginning 开始插入 Inserting at the ending 在末尾插入 Inserting at given position 在给定位置插入 Algorithms: 算法&#xff1a; 1)开始插入 (1) Inserting at the beginning) In…

mysql学习笔记(1-安装简介)

mysql的安装方式&#xff1a;(1)通过系统提供的默认版本(rpm包&#xff0c;稳定版&#xff0c;该版本满足了使用的需求&#xff0c;建议使用&#xff0c;os vendor)(2)mysql官方提供官方提供的通用rpm安装包通用二进制格式的程序包(直接下载文件&#xff0c;解压到指定目录&…