簡體   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