具有多种方法的 Codeigniter URI 路由

Codeigniter URI routing with for multiple methods

我正在研究 codeigniter。控制器名称是 "project" 并且有 4 个函数.."get_city_data", "get_store_data", "get_currency", "get_description".

我在上面 2 个函数中传递的参数是 - get_city_data($state, $city), get_place_data($state, $city, $store).

所以在浏览器上呈现这些功能我分别使用 url 作为-

http://localhost/project/get_city_data/state1/city1

我想像这样更改网址 http://localhost/state1/city1

在routes.php中如果我这样定义路由 $route['(:any)/(:any)'] = 'project/get_city_data//' 然后它也反映了所有其他函数,但我只想更改这 2 个函数的 url。

我也不想使用 _remap 函数,因为它不符合我的需求。

任何人都可以帮助我吗? 谢谢

建议你先去查查数据库,再确定需要的路由。这是我对您的要求的回答。

在您的 routes.php 中,试试这个代码:

require_once( BASEPATH . 'database/DB' . EXT );

$url_source = $_SERVER['REDIRECT_URL'];
$arr_url = explode("/", $url_source);

$state_name = $arr_url[3];
$city_name  = $arr_url[4];
$store_name = $arr_url[4];

$db = & DB();

//Let say grab 3 columns to be check
$db->select('state_name, city_name, store_name');


if(!empty($state_name)):
    $db->where('state_name', $state_name);
endif;

if(!empty($city_name)):
    $db->where('city_name', $city_name);
endif;

if(!empty($store_name)):
    $db->where('store_name', $store_name);
endif;

$query = $db->get('table', 1);
$obj = $query->row();
if ($obj):
    $route["$obj->state_name/$obj->city_name/$obj->store_name"] = "project/get_city_data/$state_name/$city_name/$store_name";
endif;

你可以通过这个url来测试一下:

http://localhost/state_name/city_name/store_name

我用正则表达式解决了这个问题。

我在routes.php中写道

$url_source = $_SERVER['REQUEST_URI'];
if(!(preg_match('%^/project/get_description\?state=[a-zA-Z_-]*%', $url_source) || preg_match('%^/project/get_currency\?state=[a-zA-Z_-]*%', $url_source))){

        if(!preg_match('%^\/[a-zA-Z_-]+\/[a-zA-Z_-]+\/[a-zA-Z_-]+$%', $url_source)){
                $route['(:any)/(:any)'] = 'project/get_city_data//';
        }else{
                $route['(:any)/(:any)/(:any)'] = 'project/get_store_data///';
        }
}

这样我就可以为特定功能路由。