Home php教程 php手册 用原生PHP写一个像CodeIgniter的路由功能

用原生PHP写一个像CodeIgniter的路由功能

Jun 13, 2016 am 09:39 AM
codeigniter routing

前段时间写了个关于手机应用的api,一直是用的query_string这种地址,而且还是根据一个act参数来区分所有的动作,这种让开发人员看起来比较费眼。本来想改写为“?c=controller&m=method&type=3&id=1” 这种形式,利用m参数来载入文件并进行实例化,后来看了sina weibo api 是对地址进行了路由。也决定跟风对地址路由。本来CI框架自己自带路由效果,但是因为考虑是写api,想写的比较纯粹一点。

支持默认控制器(index)和方法(index):

index.php
index.php/controller
index.php/controller/method
index.php/controller/method/prarme1/value1
index.php/controller/method/param1/value1/param2/value2.....
Copy after login
<?php

define('MODULE_DIR', './classes/');
$APP_PATH= str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__);    
$SE_STRING=str_replace($APP_PATH, '', $_SERVER['REQUEST_URI']);    //计算出index.php后面的字段 index.php/controller/methon/id/3
$SE_STRING=trim($SE_STRING,'/');
//echo $SE_STRING.'<br>';
//这里需要对$SE_STRING进行过滤处理。
$ary_url=array(
    'controller'=>'index',
    'method'=>'index',
    'pramers'=>array()
    );
//var_dump($ary_url);
$ary_se=explode('/', $SE_STRING);
$se_count=count($ary_se);

//路由控制
if($se_count==1 and $ary_se[0]!='' ){
    $ary_url['controller']=$ary_se[0];

}else if($se_count>1){//计算后面的参数,key-value
    $ary_url['controller']=$ary_se[0];
    $ary_url['method']=$ary_se[1];
    if($se_count>2 and $se_count%2!=0){ //没有形成key-value形式
        die('参数错误');
    }else{
        for($i=2;$i < $se_count;$i=$i+2){
            $ary_kv_hash=array(strtolower($ary_se[$i])=>$ary_se[$i+1]);
            $ary_url[pramers]=array_merge($ary_url[pramers],$ary_kv_hash);
        }
    }
}


$module_name=$ary_url['controller'];
$module_file=MODULE_DIR.$module_name.'.class.php';
//echo $module_file;
$method_name=$ary_url['method'];
if(file_exists($module_file)){
    include($module_file);
    $obj_module=new $module_name();    //实例化模块m

    if(!method_exists($obj_module, $method_name)){
        die('方法不存在');
    }else{
        if(is_callable(array($obj_module, $method_name))){    //该方法是否能被调用
            //var_dump($ary_url[pramers]);
            $get_return=$obj_module->$method_name($ary_url[pramers]);    //执行a方法,并把key-value参数的数组传过去
            if(!is_null($get_return)){ //返回值不为空
                var_dump($get_return);
            }
            
        }else{
            die('该方法不能被调用');
        }
        
    }
}
else
{
    die('模块文件不存在');
}

?>
Copy after login
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement custom middleware in CodeIgniter How to implement custom middleware in CodeIgniter Jul 29, 2023 am 10:53 AM

How to implement custom middleware in CodeIgniter Introduction: In modern web development, middleware plays a vital role in applications. They can be used to perform some shared processing logic before or after the request reaches the controller. CodeIgniter, as a popular PHP framework, also supports the use of middleware. This article will introduce how to implement custom middleware in CodeIgniter and provide a simple code example. Middleware overview: Middleware is a kind of request

How to implement API routing in the Slim framework How to implement API routing in the Slim framework Aug 02, 2023 pm 05:13 PM

How to implement API routing in the Slim framework Slim is a lightweight PHP micro-framework that provides a simple and flexible way to build web applications. One of the main features is the implementation of API routing, allowing us to map different requests to corresponding handlers. This article will introduce how to implement API routing in the Slim framework and provide some code examples. First, we need to install the Slim framework. The latest version of Slim can be installed through Composer. Open a terminal and

CodeIgniter middleware: Accelerate application responsiveness and page rendering CodeIgniter middleware: Accelerate application responsiveness and page rendering Jul 28, 2023 pm 06:51 PM

CodeIgniter Middleware: Accelerating Application Responsiveness and Page Rendering Overview: As web applications continue to grow in complexity and interactivity, developers need to use more efficient and scalable solutions to improve application performance and responsiveness. . CodeIgniter (CI) is a lightweight PHP-based framework that provides many useful features, one of which is middleware. Middleware is a series of tasks that are performed before or after the request reaches the controller. This article will introduce how to use

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

How to use the database query builder (Query Builder) in the CodeIgniter framework How to use the database query builder (Query Builder) in the CodeIgniter framework Jul 28, 2023 pm 11:13 PM

Introduction to the method of using the database query builder (QueryBuilder) in the CodeIgniter framework: CodeIgniter is a lightweight PHP framework that provides many powerful tools and libraries to facilitate developers in web application development. One of the most impressive features is the database query builder (QueryBuilder), which provides a concise and powerful way to build and execute database query statements. This article will introduce how to use Co

Use JavaScript functions to implement web page navigation and routing Use JavaScript functions to implement web page navigation and routing Nov 04, 2023 am 09:46 AM

In modern web applications, implementing web page navigation and routing is a very important part. Using JavaScript functions to implement this function can make our web applications more flexible, scalable and user-friendly. This article will introduce how to use JavaScript functions to implement web page navigation and routing, and provide specific code examples. Implementing web page navigation For a web application, web page navigation is the most frequently operated part by users. When a user clicks on the page

Implementation method and experience summary of flexibly configuring routing rules in PHP Implementation method and experience summary of flexibly configuring routing rules in PHP Oct 15, 2023 pm 03:43 PM

Implementation method and experience summary of flexible configuration of routing rules in PHP Introduction: In Web development, routing rules are a very important part, which determines the corresponding relationship between URL and specific PHP scripts. In the traditional development method, we usually configure various URL rules in the routing file, and then map the URL to the corresponding script path. However, as the complexity of the project increases and business requirements change, it will become very cumbersome and inflexible if each URL needs to be configured manually. So, how to implement in PHP

How to use routing to customize page switching animation effects in a Vue project? How to use routing to customize page switching animation effects in a Vue project? Jul 21, 2023 pm 02:37 PM

How to use routing to customize page switching animation effects in a Vue project? Introduction: In the Vue project, routing is one of the functions we often use. Switching between pages can be achieved through routing, providing a good user experience. In order to make page switching more vivid, we can achieve it by customizing animation effects. This article will introduce how to use routing to customize the page switching animation effect in the Vue project. Create a Vue project First, we need to create a Vue project. You can use VueCLI to quickly build

See all articles