【问题标题】:How to call sub folder controller with routing CodeIgniter如何使用路由 CodeIgniter 调用子文件夹控制器
【发布时间】:2012-09-15 23:35:23
【问题描述】:

我正在使用 CodeIgniter 框架。我的控制器文件夹中有这样的文件:

 - Controllers
 --- admin.php - Admin Controller
 --- /Admin - Admin Folder
 ----- category.php - Category Controller in Admin folder.

网址:mysite.com/index.php/admin/category 表示该页面未找到,因为它试图调用 admin 控制器的 category 函数,但我希望它在 Admin 中调用 category 控制器的 index 函数文件夹。

我还使用admin 控制器来创建、编辑admin 控制器等功能,例如mysite.com/index.php/admin/create

我想,我应该在配置文件中使用$route 数组。我应该使用什么路由?

【问题讨论】:

    标签: php codeigniter url-routing


    【解决方案1】:

    这是 CI 核心的默认行为。请参阅system/core/Router.php 中的function _validate_request($segments)。此函数尝试确定控制器的路径。它一一经历不同的条件,并在满足给定条件后返回结果。除此之外,还涉及两个条件:

    1. 它是一个文件吗? (system/core/Router.php 第 271 行,CI 2.1.2)

      // Does the requested controller exist in the root folder?
      if (file_exists(APPPATH.'controllers/'.$segments[0].'.php'))
      {
          return $segments;
      }
      
    2. 它是一个文件夹吗? (system/core/Router.php 第 277 行,CI 2.1.2)

      // Is the controller in a sub-folder?
      if (is_dir(APPPATH.'controllers/'.$segments[0]))
      {
          // ...
      

    在您的情况下,一旦满足两个条件中的第一个,即找到 admin.php 文件时,该函数将返回。

    有两种解决方案:

    1. 重命名文件或文件夹并分别重构应用程序。
    2. 将默认行为更改为extending the core。基本上,这将在更改条件检查的顺序时结束。这可以通过创建MY_Router 类来完成:

      class MY_Router extends CI_Router
      {
          // ...
      }
      

      并使用更改的条件序列重写原始_validate_request() 函数。所以首先检查目录,然后检查功能。

    如果不需要太多重构,我会建议第一个解决方案。

    【讨论】:

      【解决方案2】:

      在 application/config/routes.php 文件的底部,添加如下内容:

      $route['admin/create'] = 'admin/category';
      

      【讨论】:

      • 我希望从类别控制器(位于 admin 文件夹中)的索引函数中调用 admin/category。
      猜你喜欢
      • 2016-06-08
      • 2013-09-16
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      相关资源
      最近更新 更多