Search code examples
phpcodeignitercodeigniter-2

Codeigniter 2 Controller Fall Through to a different controller


I have a site I am working on that has a URL structure that looks like:

example.com/category-name

This currently goes to a 1000 line long controller called pages that was built years ago and has never been changed. I am inserting a new controller above this in the route that looks like:

$route['(:any)'] = 'new_controller/load/$1
$route['default_controller'] = "pages";

The idea is for new_controller to work like this:

example.com/page-name

This looks up page-name in a database and displays some text made by business people in the admin of the site.

The problem comes from that if page-name is not found in this table, for legacy purposes I must fall through new_controller/load and then use the pages controller normally.

For SEO reasons I can't change the URL structure, it has to remain example.com/category-name and they want it to share the same URL structure example.com/page-name because it's shorter(I tried to convince them to do something like example.com/page/page-name)

From new_controller/load/$1 how would I then call say pages/view/$1 ?

Thanks in advance it is going to really save my butt at work haha


Solution

  • In your route config you can use the config below. new_controller controller handles all page requests so long as their uris don't contain pages/view/.* which pages controller handles.

    $route['pages\/view\/(.*)'] = 'pages/view/$1';
    $route['(?!pages\/view)(.*)'] = 'new_controller/load/$1';
    

    In new_controller controller - you can do something like the code below so if the slug doesn't exist in database it will be handled by pages controller instead.

    public function load($slug)
    {
            if(/*slug in database*/){
                echo "Slug content from database";
            }
            else { // slug not in database
    
                redirect(site_url('pages/view/'.$slug)); // You can use this
                echo file_get_contents(site_url('pages/view/'.$slug)); // or this
                $this->load->view('pages_template'); // or this
                // or semething else.
            }
    }