1、大家來說說url映射吧
一般url映射有兩種方式,一種是通過mod_rewrite實作,這種網上教材很多我也不多說了。另外一種是在程式中模拟,比如類似zend framework中的那種方式/index.php/controller/action/var1/value1/var2/value2/。這裡方 式其實最主要是通過一個統一的輸入接口,然後對url進行解析,最後轉發到相應的controller中的module。
我這裡寫了兩個簡單函數來模拟。
第一個函數主要是進行位址解析,把類似/index.php/controller/action/var1/value1/var2/value2/的位址解析出來,一般來說要解析成三部分:controller,module,params。
<?php
/**
*對url路由進行簡單的解析,支援對/path/to/site/index.php/module/action/parm/value
* /path/to/site/index.php?/module/action/parm/value和
* /path/to/site/?/module/action/parm/value三種形式的處理
*@param:null
*@return:router array
*/
function url_router() {
$path = strip_tags ( $_server ['request_uri'] );
$strpos = strpos ( $path, '.php' );
if ($strpos) {
$path = substr ( $path, $strpos + 4 );
} else {
if (empty ( $_server ['query_string'] )) {
$strpos = strpos ( $path, '?' );
if ($strpos) {
$path = substr ( $path, $strpos + 1 );
} else {
$path = '';
}
} else {
$path = $_server ['query_string'];
}
}
//統一化$path的格式,如果$path的第一個字元為/則去掉
if ($path [0] == '/') {
$path = substr ( $path, 1 );
//解析,并且路由
if (! empty ( $path )) {
$path = explode ( '/', $path );
$router ['controller'] = $path [0];
$router ['action'] = (! empty ( $path [1] )) ? $path [1] : 'index';
//print_r($path);
for($i = 2; $i < sizeof ( $path ); $i = $i + 2) {
$params [$path [$i]] = (isset ( $path [$i + 1] )) ? $path [$i + 1] : '';
$router ['params'] = $params;
//預設路由資訊
$router ['controller'] = 'index';
$router ['action'] = 'index';
$router ['params'] = array ();
return $router;
}
?>
function url_dispatch($router, $app_path = '/app/controllers/') {
require_once (server_path . '/libs/controller.class.php');
$controller = $router ['controller'] . 'controller';
//echo server_path.$app_path.$controller.'.class.php';
if (! file_exists ( server_path . $app_path . $controller . '.class.php' ))
die ( '缺少必要的類!' );
require_once (server_path . $app_path . $controller . '.class.php');
$controller = new $controller ();
$controller->_setparam ( $router ['params'] );
$controller->{$router ['action'] . 'action'} ();
return true;
?>