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

时间:2012-06-17 21:38:00

标签: php codeigniter

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

  • / tutorials - >包含所有类别列表的简介页
  • / tutorials / {作为字符串的类别} - >这将给出给定类别的教程列表,例如/教程/ PHP的
  • / tutorials / {a category as string} / {an ID} / {tutorial slug} - >这将显示教程,例如/教程/ PHP / 123 /如何使用的函数
  • / tutorials / add - >页面添加新教程

问题在于,当我想使用前两种类型的URL时,我需要将参数传递给控制器​​的索引函数。第一个参数是可选类别,第二个参数是可选的教程ID。我在发布之前做过一些研究,所以我发现我可以添加tutorials/(:any)之类的路由,但问题是当使用最后一个URL时,此路由也会将add作为参数传递(/教程/添加)。

我是如何实现这一目标的?

3 个答案:

答案 0 :(得分:13)

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

$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!

答案 1 :(得分:9)

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

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

答案 2 :(得分:3)

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

在伪代码中:

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
    }
}

欢迎对此解决方案的反馈!

相关问题