2011-04-15 147 views
0

我目前有一組來自其控制器名稱的url,但它們不是很友好。CodeIgniter和友好的網址

例如,有反正更改:

example.com/admin/news_manager/add_article

example.com/admin/news-manager/add-article

任何幫助將大大ap preciated!謝謝。

+0

相關:[http://stackoverflow.com/questions/2428134/codeigniter-routes-regex/2432405#2432405](http://stackoverflow.com/questions/2428134/codeigniter-routes-regex/2432405#2432405 ) – 2011-04-15 19:18:06

回答

0

您可以使用URI路由。請參閱CodeIgniter文檔中的URI routing頁面。

1

這裏是我的,把這個在您的應用程序/核心文件夾MY_Router.php

它將所有的-'s的轉換在您的網址_的。

<?php 

class MY_Router extends CI_Router { 
    function set_class($class) 
    { 
     $this->class = $this->replace_underscores($class); 
    } 

    function set_method($method) 
    { 
     $this->method = $this->replace_underscores($method); 
    } 

    private function replace_underscores($string){ 
     return str_replace('-', '_', $string); 
    } 

    function _validate_request($segments) 
    { 
     $this->segments = $segments; 
     if(empty($this->segments) || $this->controller_is_in_root_folder()) 
      return $this->segments; 

     if ($this->controller_is_in_a_subfolder()) 
     { 
      $this->segments = $this->set_directory_and_remove_from_array(); 

      if ($this->at_least_one_segment() > 0 && !$this->default_controller_is_in_subfolder()) 
      { 
        show_404($this->fetch_directory().$this->segments[0]); 
      } 
      else 
      { 
       $this->set_class($this->default_controller); 
       $this->set_method('index'); 

       if (!$this->default_controller_is_in_subfolder()) 
       { 
        $this->directory = ''; 
        return array(); 
       } 
      } 
      return $this->segments; 
     } 
     else 
      show_404($this->segments[0]); 
    } 

    private function at_least_one_segment(){ 
     return count($this->segments) >= 1; 
    } 

    private function controller_is_in_a_subfolder(){ 
     return is_dir(APPPATH.'controllers/'.$this->segments[0]); 
    } 

    private function controller_is_in_root_folder(){ 
     return file_exists(APPPATH.'controllers/'.str_replace('-', '_', $this->segments[0]).EXT); 
    } 

    private function set_directory_and_remove_from_array(){ 
     $this->set_directory($this->segments[0]); 
     return array_slice($this->segments, 1); 
    } 

    private function default_controller_is_in_subfolder(){ 
     return file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $this->segments[0]).EXT); 
    } 
} 
1

如果它只是一個功能,你可以打開applications/config/routes.php,並添加一行是這樣的:

$route['^admin/news-manager/add-article'] = $route['admin/news_manager/add_article']; 

取決於你的其他網址,你能想出一個更通用的規則。