Welcome Guest, Not a member yet? Register   Sign In
Routing to specific controller in case controller/method is not found.
#8

Hello again;

Thanks for everyone who tried to help me in this thread. Smile I appreciate your interest.

I've solved my issue with following approach. (I know it's a little bit dirty but i couldn't find an elegant solution to this.)

PHP Code:
$route['(:any)'] = function($slug)
{
    
// find out which class(controller)/method to execute.
    
$validated $this->_validate_requestarray_values($this->uri->segments) );
    
    
// cleanup. (which set by _validate_request())
    
$directory $this->directory;
    
$this->directory NULL;

    
// extract class(controller) & method name.
    
if(array_key_exists(0,$validated))
    {
        
// class(controller) name found.
        
$class_name ucfirst($validated[0]);
    }
    else
    {
        
// class(controller) name not found. route to desired controller.
        
return 'page/view/'.$slug;
    }
    
$method_name array_key_exists(1,$validated) ? $validated[1] : 'index';
    
    
// class(controller) file to load.
    
$class_path APPPATH.'controllers/'$directory $class_name '.php';
    
    
// cleanup. (which set by _validate_request())
    
$this->directory NULL;
    
    
// class(controller) exists?
    
if(file_exists($class_path))
    {
        
// load CI_Controller core class and our class(controller).
        
include_once(FCPATH.'system/core/Controller.php');
        include_once(
$class_path);
        
        
// does method exists?
        
if(method_exists($class_name,$method_name))
        {
            
// if class(controller) and method exists, we should execute it.
            
return implode('/',$this->uri->segments);
        }
        else
        {
            
// well, if not, it's time to route to desired controller.
            
return 'page/view/'.$slug;
        }
    }
    else
    {
        
// if class(controller) doesnt exists, route to desired controller.
        
return 'page/view/'.$slug;
    }
}; 

This code works as follows:

Scenario: Physically Exists
example.com/controller/method => controllers/Controller.php->method();
example.com/controller => controllers/Controller.php->index();

Scenario: Not Exists
example.com/non-controller => controllers/page.php->view($slug);


Sub-Site Example
PHP Code:
$route['subsite/(:any)'] = /* same code as above */ 

Scenario: Physically Exists
example.com/subsite/controller/method => controllers/subsite/Controller.php->method();
example.com/subsite/controller => controllers/subsite/Controller.php->index();

Scenario: Not Exists
example.com/subsite/non-controller => controllers/page.php->view($slug);
Reply


Messages In This Thread
RE: Routing to specific controller in case controller/method is not found. - by W140 - 09-25-2015, 06:42 PM



Theme © iAndrew 2016 - Forum software by © MyBB