Стратегия перекодировки URL Codeigniter
Я работаю над проектом, встроенным в codeigniter, который интенсивно использует маршруты и функцию remap для переписывания URL. Текущая реализация запутанная и грязная.
По сути, это то, что дизайнер пытался достичь:
www.example.com/controller/method/arg1/ TO www.example.com/arg1/controller/method/
Кто-нибудь может предложить чистый способ сделать это?
На самом деле это должно происходить только для одного конкретного контроллера. Хорошо, если все остальные контроллеры должны просто следовать шаблону normal /controller/model/arg1...
Просто для того, чтобы дать вам представление о том, как текущий код выглядит здесь, это файл "маршрутов": (на самом деле я не хочу разбираться в этом коде, просто хочу дать вам представление о том, насколько беспорядочной является эта текущая установка, которую я имею в виду. с. Хочу просто выбросить это и заменить на что-нибудь получше)
// нам нужно указать контроллер администратора и функции, чтобы они не рассматривались как соревнование
$route['admin/users'] = 'admin/users';
$route['admin/users/(:any)'] = 'admin/users/$1';
$route['admin'] = 'admin/index/';
$route['admin/(:any)'] = 'admin/$1';
// same goes for sessions and any other controllers
$route['session'] = 'session/index/';
$route['session/(:any)'] = 'session/$1';
// forward http://localhost/ball/contests to controller contests method index
$route['(:any)/contests'] = 'contests/index/$1';
// forward http://localhost/ball/contests/vote (example) to controller contests method $2 (variable)
$route['(:any)/contests/(:any)'] = 'contests/index/$1/$2';
// forward http://localhost/ball/contests/users/login (example) to controller users method $2 (variable)
$route['(:any)/users/(:any)'] = 'users/index/$1/$2';
// if in doubt forward to contests to see if its a contest
// this controller will 404 any invalid requests
$route['(:any)'] = 'contests/index/$1';
$route['testing/'] = 'testing/';
И функция remap, которая идет с этим:
public function _remap($method, $params = array()){
// example $params = array('ball', 'vote')
// params[0] = 'ball', params[1] = 'vote'
/*
* Write a detailed explanation for why this method is used and that it's attempting to accomplish.
* Currently there is no documentation detailing what you're trying to accomplish with the url here.
* Explain how this moves the contest name url segment infront of the controller url segment. Also
* explain how this works with the routing class.
* */
$count = count($params);
if($count == 0){ // no contest specified
redirect('http://messageamp.com');
return;
}
$contest_name = $params[0];
unset($params[0]); //remove the contest name from params array because we are feeding this to codeigniter
if($count < 2) // no method specified
$method = 'index';
else{
$method = $params[1];
unset($params[1]);
}
//We need to scrap this, lazy-loading is a best-practice we should be following
$this->init(); //load models
//make sure contest is valid or 404 it
if(!$this->central->_check_contest($contest_name)){
show_404();
return;
}
$this->data['controller'] = 'contests';
$this->data['method'] = $method;
$this->data['params'] = $params;
// call the function if exists
if(method_exists($this, $method)){
return call_user_func_array(array($this, $method), $params);
}
show_404(); // this will only be reached if method doesn't exist
}
1 ответ
Чтобы получить что-то вроде этого:
www.example.com/controller/method/arg1/ TO www.example.com/arg1/controller/method/
Вы можете сделать это в вашем файле config.php:
$route['(:any)/(:any)/(:any)'] = "$2/$3/$1";
Однако, если вы хотите, чтобы все ваши другие классы придерживались маршрутизации по умолчанию, вам нужно будет создать маршруты для каждого из них, чтобы перезаписать этот маршрут по умолчанию:
$route['controller_name/(:any)'] = "controller_name/$1";