我正在使用 CodeIgniter (V:2.2.6),并且我有一个简单的类 User
,其中包含一些基本方法,例如 create
、update
>、编辑
、删除
和索引
。对于 index
函数,我使用参数 $user
(这是第二个 URI 段)来显示有关该用户的一些信息。所以默认 URL 如下所示:
/user/index/john
显示有关用户“john”的一些信息。
现在,我想从 URL 中删除术语“索引”,使其看起来像:
/user/john
为此,我在 paths.php 中添加了以下规则。
$route['user/(:any)'] = "user/index/$1";
它达到了目的,但它阻止访问其他功能,例如 /user/create
并自动进入 /user/index
。为了解决这个问题,除了手动添加路由规则(如
$route['user/create'] = "user/create";
对于User
类的每个方法,这一点也不酷。那么,请问有人可以建议我在当前情况下更好的路由方式吗?
这是我的代码:
<?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对于 URI 路由和另一个类似的问题 here ,但无法找到有希望的解决方案。并且请不要建议CodeIgniter版本更新。
最佳答案
我不确定这是否是您喜欢的答案,但我认为它应该有效。 只需将此函数放入您的用户 Controller 中即可。
public function _remap($method)
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->index($method);
}
}
关于CodeIgniter URI 路由 : remove method name index from URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724680/