首页 文章

Codeigniter将参数传递给控制器索引

提问于
浏览
2

我正在使用codeigniter构建一个教程系统,并希望实现以下URL结构:

  • / tutorials - >包含所有类别列表的简介页面

  • / tutorials / {作为字符串的类别} - >这将给出给定类别的教程列表,例如/教程/ PHP

  • / tutorials / {作为字符串的类别} / {一个ID} / - >这将显示教程,例如/教程/ PHP / 123 /如何使用的函数

  • / tutorials / add - >页面添加新教程

问题是,当我想使用前两种类型的URL时,我发布之前做了一些研究,所以我发现我可以添加像 tutorials/(:any) 这样的路由,但问题是这条路由会传递 add 作为使用最后一个URL(/ tutorials / add)时也是一个参数 .

我有什么想法可以实现这一目标吗?

3 回答

  • 3

    您的路由规则可以按此顺序:

    $route['tutorials/add'] = "tutorials/add"; //assuming you have an add() method
    $route['tutorials/(:any)'] = "tutorials/index"; //this will comply with anything which is not tutorials/add
    

    然后在您的控制器的index()方法中,您应该能够确定是否正在传递类别或教程ID!

  • 9

    我确实认为重新映射必须对您的问题更有用,以防您想要向控制器添加更多方法,而不仅仅是“添加” . 这应该做的任务:

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

    发布几分钟后,我想我已经找到了可能的解决方案 . (对我感到羞耻)

    在伪代码中:

    public function index($cat = FALSE, $id = FALSE)
    {
        if($cat !== FALSE) {
            if($cat === 'add') {
                $this->add();
            } else {
                if($id !== FALSE) {
                    // Fetch the tutorial
                } else {
                    // Fetch the tutorials for category $cat
                }
            }
        } else {
            // Show the overview
        }
    }
    

    欢迎提供此解决方案的反馈!

相关问题