嗨,我不会做那样的事情。
http://example.com/- 主 Controller
http://example.com/rules/- 主 Controller ,其中内容从数据库获取,但如果不存在 返回404页面。 (没关系,不是问题。)
但是如果我在 application/controlles/rules/中有子文件夹 我想将其重定向到Rules 文件夹中的主 Controller 。
下面的代码可以解决问题,但我不知道它是如何正确实现的。 在routes.php:
$route['default_controller'] = "main";
$route['404_override'] = '';
$dirtest = $route['(:any)'];
if (is_dir(APPPATH.'controllers/'.$dirtest)) {
$route['(:any)'] = $dirtest.'/$1';
} else {
$route['(:any)'] = 'main/index/$1';
}
好的,我有:
Controller /main.php
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('main_model');
}
public function index($method = null)
{
if (is_dir(APPPATH.'controllers/'.$method)) {
// Need re-rout to the application/controllers/$method/
} else {
if ($query = $this->main_model->get_content($method)) {
$data['content'] = $query[0]->text;
// it shows at views/main.php
} else {
show_404($method);
}
}
$data['main_content'] = 'main';
$this->load->view('includes/template', $data);
}
}
再次更新(routes.php): 所以,看起来就像我搜索的(工作示例):
$route['default_controller'] = "main";
$route['404_override'] = '';
$subfolders = glob(APPPATH.'controllers/*', GLOB_ONLYDIR);
foreach ($subfolders as $folder) {
$folder = preg_replace('/application\/controllers\//', '', $folder);
$route[$folder] = $folder.'/main/index/';
$route[$folder.'/(:any)'] = $folder.'/main/$1';
}
$route['(:any)'] = 'main/index/$1';
但是,非常需要这样的东西:
http://example.com/1/2/3/4/5/6/...
- 文件夹“controllers”有子文件夹“1”吗?
- 是:文件夹“1”有子文件夹“2”?
- 否:文件夹“1”有 Controller “2.php”?
- 否: Controller “controllers/1/main.php”具有函数“2”?
- 是:重定向到 http://example.com/1/2/- 其中 3,4,5 - 参数..
当你有这样的结构时,这真的很好:
http://example.com/blog/ - recent blog's posts
http://example.com/blog/2007/ - recent from 2007 year blog's posts
http://example.com/blog/2007/06/ - same with month number
http://example.com/blog/2007/06/29/ - same with day number
http://example.com/blog/web-design/ - recent blog's post's about web design
http://example.com/blog/web-design/2007/ - blog' posts about web design from 2007 years.
http://example.com/blog/current-post-title/ - current post
我发现同样有趣http://codeigniter.com/forums/viewthread/97024/#490613
最佳答案
我没有仔细阅读你的问题,但这立即引起了我的注意:
if (is_dir($path . '/' . $folder)) {
echo "$route['$folder/(:any)'] = '$folder/index/$1';"; //<---- why echo ???
}
老实说,我不确定为什么这除了无法工作之外没有给您带来严重的问题。
您不想在此处回显
路由,它只会尝试将字符串打印到屏幕上,它甚至不会以这种方式解释为PHP。引号还存在一些问题需要修复,以便变量可以被读取为变量,而不是字符串。试试这个:
if (is_dir($path . '/' . $folder)) {
$route[$folder.'/(:any)'] = $folder.'/index/$1';
}
旁白:我想提供一些与您的问题没有直接关系的额外资源,但应该可以帮助您找到解决方案:
- 将调用重新映射到 Controller 的首选方法:http://codeigniter.com/user_guide/general/controllers.html#remapping
- 扫描目录的更简单方法:http://php.net/manual/en/function.glob.php
关于php - Codeigniter 动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974756/