Codeigniter可变长度参数列表

时间:2012-07-11 14:35:27

标签: php codeigniter

我正在使用Codeigniter制作一个教程系统,但我在使用子类别进行教程时有点困惑。

URL结构是这样的:/ tutorials / test / 123 / this-is-a-tutorial

  • 教程是控制器
  • test是类别的短代码
  • 123是教程ID(在SQL查询中使用)
  • 这是一个教程只是一个美化URL
  • 的slu ..

我所做的是将类别作为第一个参数传递,将ID作为第二个参数传递给我的控制器功能:

public function tutorial($category = NULL, $tutorial_id = NULL);

现在,如果我想要子类别(无限深度),例如:/ tutorials / test / test2 / 123 / another-tutorial。我该如何实现呢?

谢谢!

3 个答案:

答案 0 :(得分:6)

为了阅读无限的论点,你至少有两个有用的工具:

所以在你的控制器中:

  • 弹出最后一段/参数(这是你的slug,不需要)
  • 假设最后一个参数是教程ID
  • 假设其余的是类别

这样的事情:

public function tutorial()
{
    $args = func_get_args();
    // ...or use $this->uri->segment_array()

    $slug = array_pop($args);
    $tutorial_id = array_pop($args); // Might want to make sure this is a digit

    // $args are your categories in order
    // Your code here
}

其余的代码和验证取决于您对参数的具体要求。

答案 1 :(得分:0)

如果您需要变量类别,可以使用URI类:$this->uri->uri_to_assoc(n)

答案 2 :(得分:0)

您可能需要考虑的另一个选项是CodeIgniter的控制器功能重新映射功能,您可以使用它来覆盖默认行为。您将能够在控制器内定义单个函数,该函数将处理对该控制器的所有调用,并将剩余的URI参数作为数组传入。然后你可以随心所欲地做任何事。

有关此事项的文档参考,请参阅here