当用户登录时,我希望他们能够访问http://website.com/user并被带到http://website.com/1/johndoe,其中1是他们的用户ID,johndoe是他们的用户名。
我尝试使用_remap()来捕获http://website.com/user/上的所有尝试,因此即使是像http://website.com/user/1或http://website.com/user/1/joh这样不完整的URI也会被重定向到http://website.com/user/1/johndoe。
这是我尝试过的:
class User extends CI_Controller {
function index($uID, $user) {
echo $uID;
echo $user;
}
function _remap() {
$uID = 3;
$user = 'johndoe';
//redirect('user/'.$uID.'/'.$user); // Updates URI, but redirect loop
//$this->index($uID, $user); Works, but doesn't update the URI
}
}当然,我可以先检测该方法,然后执行以下操作:
function _remap($method = '') {
if ($method != 'view') {
$uID = 3;
$user = 'johndoe';
redirect('user/view/'.$uID.'/'.$user);
}
}
function view($uID, $user) {
echo $uID;
echo $user;
}但是我认为URI看起来像http://website.com/user/view/1/johndoe,我宁愿view被排除在外。我该如何解决这个问题呢?
发布于 2012-11-21 22:42:45
我使用的解决方案是:
$route['user/(:num)/:any'] = 'user/view/$1';
$route['user/(:num)'] = 'user/view/$1';实际上,用户名应该只用于SEO目的,在这种情况下,不应该被传递到操作。无论如何,当您查找用户时,您当然可以从UserID访问用户名,所以我觉得这是多余的。
以上内容将匹配
/user/1/jdoe
/user/1但是只会将1传递给您的user/view操作。
编辑:考虑到你的评论:
$route['user/(:num)/(:any)'] = 'user/view/$1/$2';
$route['user/(:num)'] = 'user/view/$1';
function view($UserID, $UserName = null) {
// Load the model and get the user.
$this->model->load('user_model');
$User = $this->user_model->GetByUserID($UserID);
// If the user does not exist, 404!
if (empty($User)) {
show_404();
return;
}
// If the UserName does not exist, or is wrong,
// redirect to the correct page.
if($UserName === null || strtolower($User->UserName) != strtolower($UserName)) {
redirect("user/$UserID/{$User->UserName}");
return;
}
}上面的代码将接受用户名作为参数,但是如果没有提供或者不正确,它将重定向到正确的url并继续。
希望这能解决你的问题?
发布于 2012-11-21 22:44:57
如果你有一个_remap()方法-它总是会被调用,所以重定向到user/anything仍然会在下一个请求中调用_remap(),所以你不仅需要捕获路由器方法及其参数-如果你想以一种有意义的方式使用_remap(),你必须这样做:
public function _remap($method, $args)
{
if ($method === 'user' && (empty($args) OR ! ctype_digit($args[0])))
{
// determine and handle the user ID and name here
}
else
{
return call_user_func_array(array($this, $method), $args));
}
}https://stackoverflow.com/questions/13489879
复制相似问题