【问题标题】:CodeIgniter - Dynamic URL segmentsCodeIgniter - 动态 URL 段
【发布时间】:2012-11-16 10:18:58
【问题描述】:

我想知道是否有人可以帮助我。

我在我的 codeigniter 应用程序中构建了一个论坛,但我在弄清楚我如何构建细分市场时遇到了一些麻烦。

根据 CI 用户指南,uri 构建如下

www.application.com/CLASS/METHOD/ARGUMENTS

这很好,只是我需要将那部分结构稍微不同。

在我的论坛中,我有类别和帖子,因此要查看类别,请使用以下网址

www.application.com/forums

这很好,因为它的类名,但我想让下一个段动态,例如,如果我有一个名为“mycategory”的类别和一个名为“this-is-my-first-post”的帖子',那么结构应该是

www.application.com/forums/mycategory/this-is-my-first-post

我似乎无法做到这一点,因为根据文档,“mycategory”需要成为一种方法,即使我要执行类似 /forums/category/mycategory/this-is-my-first-post 之类的操作变得混乱。

如果有人以前做过这样的事情,请他们为我解释一下,我很坚持。

干杯,

【问题讨论】:

标签: codeigniter


【解决方案1】:

文档中没有什么令人困惑的地方,但您有点困惑。让我给你一些建议。
您创建一个视图,在其中创建要单击的超链接,并在超链接中提供此说明

<a href="www.application.com/forums/category/mycategory/this-is-my-first-post">First Post</a>

在控制器中你可以很容易地得到这个

$category = $this->uri->segment(3);
$post     = $this->uri->segment(4);

现在你可以继续了。 如果您认为您的要求是其他东西,您可以使用 hack 我为此创建了一个动态分配段的方法。

进入system/core/uri.php并添加这个方法

function assing_segment($n,$num)
{
    $this->segments[$n] =   $num;
    return $this->segments[$n];
}

如何使用

$this->uri->assign_segment(3,'mycategory');
$this->uri->assign_segment(4,'this-is-my-first-post');

如果您遇到错误“您提交的 uri 包含不允许的字符”,请转到 application/config/config.php 并添加 - 到此

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';

【讨论】:

  • 哦,第一点现在很有意义,我想我只需要有很多 if else 语句来为人们指明正确的方向,谢谢
【解决方案2】:

您可以创建一个转发到查找函数的路由。
例如,在您的 routes.php 中添加类似的行;

$route['product/(:any)/(:any)'] = "forums/cat_lookup/$1/$2";

然后,此函数将执行数据库查找以查找类别。

...
public function cat_lookup($cat, $post) {
    $catid = $this->forum_model->get_by_name($cat);
    if ($catid == FALSE) {
        redirect('/home');
    }
    $post_id = $this->post_model->get_by_name($post);
    /* whatever else you want */

    // then call the function you want or load the view
    $this->load->view('show_post');
}
...

此方法将使 URL 保持您想要的样子,并在类别不存在时处理任何问题。
不要忘记您可以使用下划线将类别/帖子存储在数据库中并使用 uri_title() 函数让他们漂亮,

【讨论】:

    【解决方案3】:
    Set in within config/routes.php 
    
    $route['song-album/(:any)/:num'] = 'Home/song_album/$id';
    
    fetch in function  with help of uri segment.
    
    $this->uri->segment(1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多