CI框架 default_controller 如何設置為:'目錄/Controller' 轉


閑談

前幾天,我的室友發現了一個問題:CI框架的Router.php文件的default_controller設置為application\controllers文件下的 一級PHP文件名 就可以,設置為 目錄/Controller名 就 404,如目錄結構:

----application
   | ----controllers | -----admin | | ---------Welcome.php | ----Welcome.php 

在application\config下的routes.php,配置如下

$route['default_controller'] = 'welcome'; 這樣就可以 $route['default_controller'] = 'admin/welcome'; 這樣不可以 

一開始以為是哪里配置錯了,但沒道理啊,主要的只有這個配置。我開始懷疑是CI版本的問題,到網上一查,果然有相同問題的道友,不過沒有找到確切的解決方案,也許是應為安全性的問題,3.x 版本的都不能這樣設置了。

正題

博主嘗試着決解這個問題。博主的CI版本為3.1.4

看了源碼才知道原來 $route['default_controller'] 的值是 '類名/方法名' 而不是 '路徑/類名'

打開system\core目錄下的Router.php, 大概在298行

//將下面的代碼注釋掉 /** if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) { $method = 'index'; } **/ //並上面的代碼后面加上 下面的代碼 $index = strripos($this->default_controller, '/'); // 記錄 符號‘/’的下標 if($index == false){ $class = $this->default_controller; // 沒有‘/’ 的可以直接賦值 }else{ $this->directory = substr($this->default_controller, 0, $index + 1); //目錄的字符串 $class = substr($this->default_controller, $index + 1); //類的字符串 } $method = $this->method; //默認方法 

如果是 '路徑/類名' ,以上的配置就夠了

添加Controller默認的方法名

當然可以設置默認的方法名 , 一般是index,如果要改也是可以的
在application\config下的routes.php,添加

$route['method'] = 'index'; //默認的方法名 

在system\core目錄下的Router.php,大概在176行,添加

if (isset($route) && is_array($route)) { isset($route['default_controller']) && $this->default_controller = $route['default_controller']; isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes']; unset($route['default_controller'], $route['translate_uri_dashes']); $this->routes = $route; isset($route['method']) && $this->method = $route['method']; // 添加這一句代碼就可以了 } 

這樣就可以了,希望對你有幫助。



作者:止境_af83
鏈接:https://www.jianshu.com/p/e6615ee734e7
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM