2012-08-30 16 views
1

這個問題可能存在其他地方,如果有的話,我表示歉意。在找了一個小時沒有成功之後,我忍不住想我走錯了路。如何使用CodeIgniter執行描述性URL?

基本上我正在尋找的是一種強制在頁面URL中描述或標題的方法。我使用的是CodeIgniter,所以將一個漂亮的URL放到我希望的地方很簡單。

我可以有:

http://mysite.com/controller/function/what-ever-i-want/can-go-here 

,它會經常去:

http://mysite.com/controller/function/ 

與變量值what-ever-i-wantcan-go-here

我想什麼是網址是如果只給出控制器/功能,則自動重寫爲包括標題。

因此,如果有人去:

http://mysite.com/controller/function/ 

它會自動重寫URL作爲

http://mysite.com/controller/function/a-more-descriptive-title/ 

的,我說的是SO URL的功能一個很好的例子。如果你去https://stackoverflow.com/questions/789439它會自動重寫它到https://stackoverflow.com/questions/789439/how-can-i-parse-descriptive-text-to-a-datetime-object

我懷疑涉及mod_rewrite,但我想想出解決方案CodeIgniter最適合地工作。

我是很新的漂亮的URL現場,在別人的建議更有經驗拼命地叫。預先感謝您提供的任何幫助!

回答

1

我用Fiddler2來看看Stackoverflow如何做到這一點。從http://stackoverflow.com/questions/12205510/

HTTP/1.1 301 Moved Permanently 
Location: /questions/12205510/how-can-i-enforce-a-descriptive-url-with-codeigniter 
Vary: * 
Content-Length: 0 

的respnse的

部分所以基本上我們去的時候controller/function/我們需要用戶重定向到controller/function/my-awesome-title。我已經寫了簡單的控制器,做到了這一點:

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class Controller extends CI_Controller 
{ 
    protected $_remap_names = array(); 

    function __construct() 
    { 
     parent::__construct(); 

     $this->_remap_names['func'] = "My Awesome Title"; 
    } 

    function _remap($method, $arguments) 
    { 
     if(
      isset($this->_remap_names[$method]) 
      && sizeof($arguments) == 0 
      && method_exists($this, $method) 
      ) 
     { 

      $this->load->helper("url"); 

      $title = str_replace(" ", "-", $this->_remap_names[$method]); 
      $title = strtolower($title); 

      $url = strtolower(__CLASS__)."/$method/$title"; 
      $url = site_url($url); 

      // if you dont want to have index.php in url 
      $url = preg_replace("/index\.php\//", "", $url); 

      header("HTTP/1.1 301 Moved Permanently"); 
      header("Location: $url"); 
      header("Vary: *"); 
     } 
     else 
     { 
      call_user_func_array(array($this,$method), $arguments); 
     } 
    } 

    function func() 
    { 
     echo "<h1>"; 
     echo $this->_remap_names[__FUNCTION__]; 
     echo "</h1>"; 
    } 

}; 

Google文檔CodeIgniters _remap功能可以重新映射函數調用部分中找到here

+1

非常全面的迴應。我想我可以稍微修改這個以適應我的應用程序! – VictorKilo

1

我不使用笨,但你應該能夠放在一個控制器的__construct代碼,或在某種預作用的事件,如果CI有那麼些。

您只需查找正在查看的實體的適當URL並根據需要執行301重定向。

+0

哇,這其實很簡單......我可以輸出'頭(「HTTP/1.1 301永久移動」);'和'頭(「地點:http://www.mysite.com/controller/function /標題到頁」);'的__construct內()如果沒有額外的參數中給出。謝謝! – VictorKilo