如何使用路由CodeIgniter调用子文件夹控制器 [英] How to call sub folder controller with routing CodeIgniter
问题描述
我正在使用CodeIgniter框架。我的控制器文件夹中有这样的文件:
I am using CodeIgniter framework. I have files in my controllers folder like this:
- Controllers
--- admin.php - Admin Controller
--- /Admin - Admin Folder
----- category.php - Category Controller in Admin folder.
网址: mysite.com/index.php/admin/category
表示找不到该页面,因为它正在尝试调用 admin
控制器的类别
函数,但是我希望它在 Admin $ c $中调用
类别
控制器的 index
函数c>文件夹。
The Url: mysite.com/index.php/admin/category
says that page not found because it is trying to call the category
function of admin
controller but I want it to call the index
function of category
controller in Admin
folder.
我也正在使用 admin
控制器来创建,编辑<$ c等功能$ c> admin 控制器,例如 mysite.com/index.php/admin/create
。
Also I am using the admin
controller for create, edit etc. functions of admin
controller like mysite.com/index.php/admin/create
.
我认为,我应该在配置文件中使用 $ route
数组。我应该使用哪种路由?
I think, I should use the $route
array in config file. What routing should I use?
推荐答案
这是CI核心的默认行为。请参见 system / core / Router.php
中的函数_validate_request($ segments)
。此功能尝试确定到控制器的路径。它一一经历不同的条件,并在满足给定条件时返回结果。除其他条件外,还涉及两个条件:
This is the default behavior of the CI core. See function _validate_request($segments)
in system/core/Router.php
. This function attempts to determine the path to the controller. It goes through different conditions one by one and returns the result once a given condition is met. Besides the other, there are two conditions involved:
-
它是文件吗? (
system / core / Router.php
第271行,CI 2.1.2)
Is it a file? (
system/core/Router.php
line 271, CI 2.1.2)
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].'.php'))
{
return $segments;
}
是文件夹吗? ( system / core / Router.php
第277行,CI 2.1.2)
Is it a folder? (system/core/Router.php
line 277, CI 2.1.2)
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// ...
在您的情况下,函数将在两个条件中的第一个满足时返回,即当<$ c $找到c> admin.php 文件。
In your case the function will return once the first of the two conditions is met, i.e. when admin.php
file is found.
有两种解决方案:
- 重命名文件或文件夹并分别重构应用程序。
-
通过扩展核心。从根本上说,这将改变条件检查的顺序。这可以通过创建
MY_Router
类来实现:
- Rename the file or the folder and refactor the application respectively.
Change the default behavior by extending the core. Basically that would conclude in changing the sequence of conditions checking. This can be accomplished by creating
MY_Router
class:
class MY_Router extends CI_Router
{
// ...
}
并重写原始的 _validate_request()
函数,其条件序列已更改。因此,首先检查目录,然后检查功能。
and rewriting the original _validate_request()
function with changed sequence of conditions. So first checking for directory and then for function.
我建议第一个解决方案,如果不需要的话重构。
I would suggest the first solution, if it does not require too much refactoring.
这篇关于如何使用路由CodeIgniter调用子文件夹控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!