【问题标题】:Remove CodeIgniter controller name, index.php to just show default controller method names (with hyphens)删除 CodeIgniter 控制器名称 index.php 以仅显示默认控制器方法名称(带连字符)
【发布时间】:2013-02-13 04:09:20
【问题描述】:

我愿意

  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';

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

有什么想法吗?

提前谢谢..

乔恩。

【问题讨论】:

  • 好问题。谢谢

标签: php codeigniter


【解决方案1】:

您可以通过扩展路由器类来更改网址以接受连字符。
在 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。

【讨论】:

  • 你需要 .htaccess 从 url 中删除 index.php
  • 是的,对不起 - 虽然这是给定的,但没有正确阅读问题。删除 index.php 是基本的东西,被覆盖了,这里不再赘述。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 2011-08-04
  • 2018-01-10
相关资源
最近更新 更多