1

我想

  1. 从 URL 中删除默认控制器名称
  2. 从 URL 中删除 index.php
  3. 将带下划线的方法名转换为带连字符的方法名

在下面的示例中,fudev 是根目录下的子目录,而 preview 是 codeigniter 所在的目录。

目前:http ://devsite.com/fudev/preview/index.php/controllername/method_name 。

我希望有:

http://devsite.com/fudev/preview/method-name

有任何想法吗?我在 config/routes.php 中有以下内容将方法名称更改为连字符

$route['controllername/method-name'] = 'controllername/method_name';

..但这只有在我包含我想省略的控制器名称时才有用。

有任何想法吗?

提前致谢..

乔恩。

4

1 回答 1

0

您可以通过扩展 Router 类来更改 url 以接受连字符。
在 application/core 中创建一个名为 MY_Router.php 的文件(假设您没有更改在配置中设置的默认扩展前缀。

该文件的代码是;

<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Router extends CI_Router {

    function set_class($class) {
        $this->class = str_replace('-', '_', $class);
    }

    function set_method($method) {
        $this->method = str_replace('-', '_', $method);
    }

    function _validate_request($segments) {
        // Does the requested controller exist in the root folder?
        if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).'.php')) {
            return $segments;
        }
        // Is the controller in a sub-folder?
        if (is_dir(APPPATH.'controllers/'.$segments[0])) {       
            // Set the directory and remove it from the segment array
            $this->set_directory($segments[0]);
            $segments = array_slice($segments, 1);

            if (count($segments) > 0) {
                // Does the requested controller exist in the sub-folder?
                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).'.php')) {
                    show_404($this->fetch_directory().$segments[0]);
                }
            } else {
                $this->set_class($this->default_controller);
                $this->set_method('index');

                // Does the default controller exist in the sub-folder?
                if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) {
                    $this->directory = '';
                    return array();
                }

            }

            return $segments;
        }

        // Can't find the requested controller...
        show_404($segments[0]);
    }
}

这会将所有连字符重新映射为控制器的下划线,无需使用 htaccess。

于 2013-02-27T12:07:33.623 回答