【问题标题】:CodeIgniter URI Routing: remove method name index from URLCodeIgniter URI 路由:从 URL 中删除方法名称索引
【发布时间】:2017-04-05 02:44:36
【问题描述】:

我正在使用 CodeIgniter (V:2.2.6),我有一个简单的类 User,其中包含一些基本方法,例如 createupdateeditdeleteindex。对于index 函数,我使用参数$user(这是第二个URI 段)来显示有关该用户的一些信息。因此默认 URL 如下所示:

/user/index/john

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

现在,我想从 URL 中删除术语“索引”,使其看起来像:

/user/john

为此,我在 routes.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 版本更新。

【问题讨论】:

  • 为什么在列表中最后添加 (:any) 的特定路由以创建、更新等是“不酷”?输入它们不会让你的键盘磨损。
  • @TimBrownlaw 好吧,为了演示,我将函数列表保持得更小。考虑一个现实生活场景,其中一个类中的方法数量可能是 10、20 或 30。

标签: codeigniter url routing uri url-routing


【解决方案1】:

我不确定,如果这是您喜欢的答案,但我认为它应该有效。 只需将此函数放在您的用户控制器中即可。

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

【讨论】:

  • 感谢您的回答。重新映射函数调用 (codeigniter.com/userguide2/general/controllers.html#remapping) 听起来肯定比手动添加路由规则更好。
  • 好的,谢谢您接受 - 但请记住,您应该防止创建用户名,如创建、更新、删除、插入和索引。
  • CI3 有这个问题,或者我的 mamp 配置不支持某些东西,我遇到了与以前在其他 Web 应用程序上默认工作的索引相同的问题。这个sn-p是必须的。谢谢@sintakonte!
猜你喜欢
  • 1970-01-01
  • 2011-09-05
  • 2023-03-04
  • 2020-07-03
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多