CodeIgniter URI 路由:从 URL 中删除方法名称索引

CodeIgniter URI Routing: remove method name index from URL

我正在使用 CodeIgniter (V:2.2.6),我有一个简单的 class User 和一些基本方法,例如 createupdateeditdeleteindex。对于 index 函数,我使用参数 $user(这是第二个 URI 段)来显示有关该用户的一些信息。所以默认的 URL 看起来像:

/user/index/john

显示有关用户的一些信息'john'。

现在,我想从 URL 中删除术语 'index',使其看起来像:

/user/john

为此,我在 routes.php 中添加了以下规则。

$route['user/(:any)'] = "user/index/";

它达到了目的,但它会阻止访问 /user/create 等其他功能并自动进入 /user/index 内部。要解决这个问题,除了手动添加

之类的路由规则外,我看不到任何其他方法
$route['user/create'] = "user/create";

对于 User class 的每个方法,这一点都不酷。那么,请问有人能建议我在当前情况下更好的路由方式吗?

这是我的代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
    public function index($user = '') {
        echo "index!";
    }

    public function create() {
        echo 'create!';
    }
}

注意:我已经浏览了 CodeIgniter documentation for URI Routing and another similar question here,但找不到有前途的解决方案。并且请不要建议 CodeIgniter 版本更新。

我不确定这是否是您喜欢的答案,但我认为它应该可行。 只需将此功能放入您的用户控制器即可。

public function _remap($method)
{
    if (method_exists($this, $method))
    {
        $this->$method();
    }
    else
    {
        $this->index($method);
    }
}