Jacob Haug
Jacob Haug

Reputation: 519

CodeIgniter - Organizing Controllers into Subfolders

I'm building a site using CodeIgniter and up until now things have been going great. However, recently one of my controllers has been growing in size. I'd like to split the controller up into separate files within a sub-folder. Right now I have the following....

/controller/dashboard.php

Within that controller I have a function for the different sections. I check run a check to see if a usergroup has permissions to a section...etc. So, the URL might be something like this...

/dashboard/pages/add

I know I can setup a subfolder and have my URL be like the following....

/dashboard/staff/pages/add

But, I'd like to omit the 'usergroup' if at all possible. I'd like to do this by the following....

/controllers/dashboard/ -> If staff load staff.php, if user load user.php...etc.

I can't do the following either....

$this->load->controller();

How would you suggest I setup a dashboard area? Each usergroup has different things they need to access. Putting everything in one document is getting too long, and separating them out means I have to put the usergroup in the URL....yucky.

Is it possible to run a check in routes.php?

if ($this->user_model->is_user()) {
  // load this controller
}

Hoping you guys will have some ideas for me!

Thanks, Jacob

Upvotes: 0

Views: 1048

Answers (1)

Damien Pirsy
Damien Pirsy

Reputation: 25435

Well, a quick and dirty solution might using a redirect in a master controller...

Create a "dashboard" controller inside controller/:

class Dashboard extends CI_Controller {

function index()
{
  //make a check for the user that returns the usergroup:
  $user = $this->user_model->is_user();
  redirect('controller/'.$user.'/'.$user);
}

}

wich basically whenever an admin goes to http://www.mysite.com/index.php/dashboard it just redirects to the corresponding user controller inside the folder controller. So if your check returns "staff", it will redirect to controller/staff/staff.php and so on..

As far as I know you can't user custom expressions like that inside the router config.

Another possible solution is using hooks. You might use a pre_controller hook

pre_controller Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.

Something like

$hook['pre_controller'][] = array(
                                'class'    => 'Select',
                                'function' => 'get_usergroup',
                                'filename' => 'Select.php',
                                'filepath' => 'hooks');

And you create a Select.php class file inside the application/hooks folder with a method get_usergroup() which grabs from the session or from a model the usergroup and do the needed redirect.

Upvotes: 1

Related Questions