我想
- 从URL中删除默认控制器名称
- 从URL中删除index.php
- 将带下划线的method_name转换为带连字符的method-name
在下面的例子中,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';
. .但这只有在包含controllername时才有用,我想省略它。
任何想法?
Thanks in advance.
Jon。你可以通过扩展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