How to call sub folder controller with routing CodeIgniter

醉酒当歌 提交于 2019-12-13 00:41:02

问题


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.

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.

Also I am using the admin controller for create, edit etc. functions of admin controller like mysite.com/index.php/admin/create.

I think, I should use the $route array in config file. What routing should I use?


回答1:


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:

  1. 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;
    }
    
  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]))
    {
        // ...
    

In your case the function will return once the first of the two conditions is met, i.e. when admin.php file is found.

There are two solutions:

  1. Rename the file or the folder and refactor the application respectively.
  2. 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
    {
        // ...
    }
    

    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.




回答2:


At the bottom of your application/config/routes.php file, add something like this:

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


来源:https://stackoverflow.com/questions/12443275/how-to-call-sub-folder-controller-with-routing-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!