CodeIgniter和友好的网址

时间:2011-04-15 15:31:30

标签: codeigniter friendly-url

我目前有一组网址来自他们的控制器名称,但它们不是非常友好的网址。

例如,无论如何我改变了:

  

example.com/admin/news_manager/add_article

  

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

任何帮助将不胜感激!谢谢。

3 个答案:

答案 0 :(得分: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 :(得分:1)

如果仅仅是一个功能,您可以打开applications/config/routes.php并添加如下所示的行:

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

取决于您的其他网址,您可以提出更通用的规则。

答案 2 :(得分:0)

您可以使用URI路由。请参阅CodeIgniter文档中的URI routing页面。