php url 调度

Jun 23, 2016 pm 02:34 PM

1, 支持非rewrite即:
http://localhost/index.php/blog/view/5456-asdf.html
也可以被正确解析。。
-----------------------------------
2,增加:绝对地址生成 只要 
rurl('myFirstRouter', array('id' => '33', 'name' => 'thename'), true);
最后多加一个true,默认为false即相对地址。
生成绝对地址如:网站根目录/fleaphp/test/blog/view/33-thename.html

修改自ZendFramework的Router_Regexp类。
花了点时间整理的,水平有限,希望有高人能完善一下。

定义一个路由跟定义DSN一样的方法:

return array( 'routers' =>array(   'myFirstRouter' => array(    'blog/view(?:/(\d+)-(.+))\.html',    array(     'id'   => '1',     'controller'  => 'default',     'action'  => 'index'    ),    array(     1 => 'id',     2 => 'name'    ),    'blog/view/%d-%s.html'   ),   'mySecondRouter' => array(    'blog(?:/(\d+)-(.+))\.html',    array(     'id'   => '1',     'controller'  => 'default',     'action'  => 'index'    ),    array(     1 => 'id',     2 => 'name'    ),    'blog/%d-%s.html'   ),   'myThirdRouter' => array(    '([a-z0-9]+)/([a-z0-9]+)',    array(),    array(     1 => 'controller',     2 => 'action'    ),    'blog/%d-%s.html'   )   ) );

复制代码 是一个二维数组,每一个值为一条路由规则。
其中第一项是正则表达式,第二项为:参数默认值(这里可以设置controller,action,及其它参数的默认值。)
第三项为:参数的对应关系,与第一项的正则表达里面匹配元素对应。
第四项用于生成链接时候使用的格式。如果没看明白,可以看ZF的Router一节。

先发改的My_Dispatcher_Regexp类的代码:

loadRouters();         if (! is_array($this->_routers)) return false;         if (!$this->_pathInfo) $this->getPathInfo();                  foreach (array_reverse($this->_routers) as $router) {          if (! is_array($router)) continue;          if ($router[0] == '' || !is_string($router[0])) continue;          $regexp = '#^' . $router[0]. '$#i';    if (! isset($router[1])) $router[1] = array();          if (! isset($router[2])) $router[2] = array();          if ($args = $this->match($regexp, $this->_pathInfo, $router[1], $router[2])) {           $this->_curRouter = $router;           $data['controller'] = $args['controller'];           $data['action'] = $args['action'];           $_GET = array_merge($_GET, $args);           break;          }         }         $this->_request = $data;     }     /**      * 载入路由数据信息      *      */     function loadRouters() {      static $routerLoaded;      if ($routerLoaded) return;      $routerLoaded = false;      $routerConfig = FLEA::getAppInf('routerConfig');         FLEA::loadAppInf($routerConfig);         $this->_routers = FLEA::getAppInf('routers');         $routerLoaded = true;     }     /**      * 根据服务器环境不同,取得RequestUri信息      *      * @return unknown      */     function getRequestUri() {      if ($this->_requestUri) return $this->_requestUri;         if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch             $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];         } elseif (isset($_SERVER['REQUEST_URI'])) {             $requestUri = $_SERVER['REQUEST_URI'];         } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI             $requestUri = $_SERVER['ORIG_PATH_INFO'];             if (!empty($_SERVER['QUERY_STRING'])) {                 $requestUri .= '?' . $_SERVER['QUERY_STRING'];             }         } else {          $requestUri = null;         }         $this->_requestUri = $requestUri;         return $requestUri;     }     function getBaseUrl() {      if ($this->_baseUrl) return $this->_baseUrl;         $filename = basename($_SERVER['SCRIPT_FILENAME']);         if (basename($_SERVER['SCRIPT_NAME']) === $filename) {             $baseUrl = $_SERVER['SCRIPT_NAME'];         } elseif (basename($_SERVER['PHP_SELF']) === $filename) {             $baseUrl = $_SERVER['PHP_SELF'];         } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $filename) {             $baseUrl = $_SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility         } else {             // Backtrack up the script_filename to find the portion matching             // php_self             $path    = $_SERVER['PHP_SELF'];             $segs    = explode('/', trim($_SERVER['SCRIPT_FILENAME'], '/'));             $segs    = array_reverse($segs);             $index   = 0;             $last    = count($segs);             $baseUrl = '';             do {                 $seg     = $segs[$index];                 $baseUrl = '/' . $seg . $baseUrl;                 ++$index;             } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));         }         // Does the baseUrl have anything in common with the request_uri?         $requestUri = $this->getRequestUri();         if (0 === strpos($requestUri, $baseUrl)) {             // full $baseUrl matches             $this->_baseUrl = $baseUrl;             return $this->_baseUrl;         }         if (0 === strpos($requestUri, dirname($baseUrl))) {             // directory portion of $baseUrl matches             $baseUrl = rtrim(dirname($baseUrl), '/');             $this->_baseUrl = $baseUrl;             return $this->_baseUrl;         }         if (!strpos($requestUri, basename($baseUrl))) {             // no match whatsoever; set it blank             $this->_baseUrl = '';             return $this->_baseUrl;         }         // If using mod_rewrite or ISAPI_Rewrite strip the script filename         // out of baseUrl. $pos !== 0 makes sure it is not matching a value         // from PATH_INFO or QUERY_STRING         if ((strlen($requestUri) >= strlen($baseUrl))             && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0)))         {             $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));         }        $baseUrl = rtrim($baseUrl, '/');         $this->_baseUrl = $baseUrl;         return $this->_baseUrl;         }     function getPathInfo () {         $baseUrl = $this->getBaseUrl();         if (null === ($requestUri = $this->getRequestUri())) {             return null;         }         // Remove the query string from REQUEST_URI         if ($pos = strpos($requestUri, '?')) {             $requestUri = substr($requestUri, 0, $pos);         }         if ((null !== $baseUrl)             && (false === ($pathInfo = substr($requestUri, strlen($baseUrl)))))         {             // If substr() returns false then PATH_INFO is set to an empty string             $pathInfo = '';         } elseif (null === $baseUrl) {             $pathInfo = $requestUri;         }         $this->_pathInfo = $pathInfo;         return $pathInfo;     }          /**      * Matches a user submitted path with a previously defined route.      * Assigns and returns an array of defaults on a successful match.      *      * @param string Path used to match against this routing map      * @return array|false An array of assigned values or a false on a mismatch      */     function match($regex, $path, $defaults, $map)     {         $path = trim(urldecode($path), '/');         $res = preg_match($regex, $path, $values);         if ($res === 0) return false;         foreach ($values as $i => $value) {             if (!is_int($i) || $i === 0) {                 unset($values[$i]);             }         }         $values = $this->_getMappedValues($map, $values);         $defaults = $this->_getMappedValues($map, $defaults, false, true);         $return = $values + $defaults;         return $return;     }     /**      * Maps numerically indexed array values to it's associative mapped counterpart.      * Or vice versa. Uses user provided map array which consists of index => name      * parameter mapping. If map is not found, it returns original array.      *      * Method strips destination type of keys form source array. Ie. if source array is      * indexed numerically then every associative key will be stripped. Vice versa if reversed      * is set to true.      *      * @param array Indexed or associative array of values to map      * @param boolean False means translation of index to association. True means reverse.      * @param boolean Should wrong type of keys be preserved or stripped.      * @return array An array of mapped values      */     function _getMappedValues($map, $values, $reversed = false, $preserve = false)     {         if (count($map) == 0) {             return $values;         }         $return = array();         foreach ($values as $key => $value) {             if (is_int($key) && !$reversed) {                 if (array_key_exists($key, $map)) {                     $index = $map[$key];                 } elseif (false === ($index = array_search($key, $map))) {                     $index = $key;                 }                 $return[$index] = $values[$key];             } elseif ($reversed) {                 $index = (!is_int($key)) ? array_search($key, $map, true) : $key;                 if (false !== $index) {                     $return[$index] = $values[$key];                 }             } elseif ($preserve) {                 $return[$key] = $value;             }         }         return $return;     }     /**      * Assembles a URL path defined by this route      *      * @param array An array of name (or index) and value pairs used as parameters      * @return string Route path with user submitted parameters      */     function assemble($defaults, $map = array(), $reverse, $data = array())     {         if ($reverse === null) {             return '构建网址失败!路由参数错误!';            }              $data = $this->_getMappedValues($map, $data, true, false);         $data += $this->_getMappedValues($map, $defaults, true, false);         //$data += $this->_values;         ksort($data);         $return = @vsprintf($reverse, $data);         if ($return === false) {             return '构建网址失败!';           }         return $return;     }     /**      * 使用路由构建网址      */     function url($routerName, $urlOptions, $absolute) {      $this->loadRouters();      if (isset($this->_routers[$routerName])) $curRouter = $this->_routers[$routerName];      elseif (isset($this->_curRouter)) $curRouter = $this->_curRouter;   if (is_array($curRouter) && count($curRouter) == 4 && is_string($curRouter[3])) {    $defaults = $curRouter[1];    $map = $curRouter[2];    $reverse = $curRouter[3];   } else {    return '构建网址失败!路由参数错误!';   }      if (is_array($map) && is_string($reverse))       if (!$absolute) return $this->assemble($defaults, $map, $reverse, $urlOptions);       else {        if (!$this->_baseUrl) $this->getBaseUrl();        return $this->_baseUrl . '/' .$this->assemble($defaults, $map, $reverse, $urlOptions);       }     } }

复制代码 这里要说一个比较好的自定义类的命名规则及文件放置位置。
在FLEA下面建一个My的目录里面放自已的类。比如My_Dispatcher_Regexp放在:
My/Dispatcher/Regexp.php

同时为方便写一个生成网址助手:
My_Helper_Router
My/Helper/Router.php
代码如下:

url($routerName, $urlOptions, $absolute); }

复制代码 使用方法:
/* 修改默认的Dispatcher为自定义的Dispatcher类*/
FLEA::setAppInf('dispatcher','My_Dispatcher_Regexp');

/* 设置路由配置信息的文件位置*/
FLEA::setAppInf('routerConfig', './APP/config/router.php');

其它代码跟任何一个普通的例子一样。

controller里面代码如下:

复制代码

我们在view中用下面代码:

'33', 'name' => 'thename'));

复制代码 就可以看到$_GET得到正确的参数,
rurl也生成我们期望的网址:
blog/view/33-thename.html

绝对网址生成方法如下:

rurl('myFirstRouter', array('id' => '33', 'name' => 'thename'),true); //将生成如下的网址: /other/fleaphp/test/blog/view/33-thename.html 如果没有使用apache的mod_rewrite功能生成的网址如下: /fleaphp/test/index.php/blog/view/33-thename.html

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) 11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) Mar 03, 2025 am 10:49 AM

종종 키워드와 추적 매개 변수로 혼란스러워하는 긴 URL은 방문자를 방해 할 수 있습니다. URL 단축 스크립트는 솔루션을 제공하여 소셜 미디어 및 기타 플랫폼에 이상적인 간결한 링크를 만듭니다. 이 스크립트는 개별 웹 사이트 a에 유용합니다

Instagram API 소개 Instagram API 소개 Mar 02, 2025 am 09:32 AM

Instagram은 2012 년 Facebook에서 유명한 인수에 이어 타사 사용을 위해 두 개의 API 세트를 채택했습니다. Instagram Graph API 및 Instagram Basic Display API입니다. 개발자는

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

Laravel Back End : Part 2, React가있는 React 앱 구축 Laravel Back End : Part 2, React가있는 React 앱 구축 Mar 04, 2025 am 09:33 AM

이것은 Laravel 백엔드가있는 React Application을 구축하는 데있어 시리즈의 두 번째이자 마지막 부분입니다. 이 시리즈의 첫 번째 부분에서는 기본 제품 목록 응용 프로그램을 위해 Laravel을 사용하여 편안한 API를 만들었습니다. 이 튜토리얼에서는 Dev가 될 것입니다

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

2025 PHP 상황 조사 발표 2025 PHP 상황 조사 발표 Mar 03, 2025 pm 04:20 PM

2025 PHP Landscape Survey는 현재 PHP 개발 동향을 조사합니다. 개발자와 비즈니스에 대한 통찰력을 제공하는 프레임 워크 사용, 배포 방법 및 과제를 탐색합니다. 이 조사는 현대 PHP Versio의 성장을 예상합니다

See all articles