1

そうしたいです。

  1. URLからデフォルトのコントローラー名を削除します
  2. URLからindex.phpを削除します
  3. アンダースコア付きの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';

..しかし、それは、省略したいコントローラー名を含める場合にのみ有効です。

何か案は?

前もって感謝します..

ジョン。

4

1 に答える 1

0

Router クラスを拡張することで、ハイフンを受け入れるように URL を変更できます。
application/core に MY_Router.php というファイルを作成します (config.xml で設定されているデフォルトの拡張子プレフィックスを変更していないと仮定します)。

このファイルのコードは次のとおりです。

<?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 に答える