Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default controller inside subfolder codeigniter 3 not working

In codeigniter 3 application i have directory structure like this:

-Myproject
  -application
    -controllers
     -home
       Welcome.php   //This is my controller inside home directory

How to set Welcome controller as default controller? I use below code

$route['default_controller'] = 'home/Welcome';

This routing works for previous versions of codeigniter.

like image 748
codex Avatar asked May 22 '15 12:05

codex


2 Answers

By default, you are not allowed to do that. To get around this, you need to hack your system Router.php:

codeigniter/system/core/Router.php

Edit a few lines of code so that it becomes like this:

codeigniter/system/router.php

line 1. if (!sscanf($this->default_controller, '%[^/]/%[^/]/%s', $directory, $class, $method) !== 2)

line 2. if ( ! file_exists(APPPATH.'controllers'. DIRECTORY_SEPARATOR . $directory. DIRECTORY_SEPARATOR .ucfirst($class).'.php'))

line 3. $this->set_directory($directory);

Once you've done, you can call the default controller under directory.

$route['default_controller'] = 'home/Welcome';

like image 175
nurulhudamustaqim Avatar answered Sep 24 '22 06:09

nurulhudamustaqim


You need not to change anything from files inside CODEIGNITER system folder. Codeigniter allows developer to extend their feature. You can create a file named as MY_Router.php.

<?php
class MY_Router extends CI_Router {
    protected function _set_default_controller() {

        if (empty($this->default_controller)) {

            show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
        }
        if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) {
            $method = 'index';
        }
        if( is_dir(APPPATH.'controllers/'.$class) ) {
            $this->set_directory($class);
            $class = $method;
            if (sscanf($method, '%[^/]/%s', $class, $method) !== 2) {
                $method = 'index';
            }
        }

        if ( ! file_exists(APPPATH.'controllers/'.$this->directory.ucfirst($class).'.php')) {
            return;
        }
        $this->set_class($class);
        $this->set_method($method);
        $this->uri->rsegments = array(
            1 => $class,
            2 => $method
        );
        log_message('debug', 'No URI present. Default controller set.');
    }
}

Note: Do not change the file name.

like image 28
Sugan Krishna Avatar answered Sep 26 '22 06:09

Sugan Krishna