繁体   English   中英

CodeIgniter-动态URL段

[英]CodeIgniter - Dynamic URL segments

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

我在我的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之类的操作,也仍然会造成混淆。

如果有人以前曾经做过这样的事情,请给我一点点启示,我对此很执着。

干杯,

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

<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);

现在您可以继续。 如果您认为您的需求是其他东西,则可以使用技巧,我为此创建了一种动态分配细分的方法。

转到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~%.:_\-';

您可以进行转发到查找功能的路由。
例如,在您的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()函数使它们漂亮,

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM