Search code examples
phpcodeigniterurl-routing

php: Routing in CI (Codeigniter)


I really have a hard time understanding the URL/URI routing in CI. In this instance, I have two links, one is Home and the other is Panel, Home links to main/index and panel links to main/panel, heres the snippet to better understand.

<a href="main/index"> Home </a>
<a href="main/panel"> Panel </a>

and this is the code for the controller main.php

class Main extends CI_Controller
{
    public function index()
    {
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->view('templates/header');
        $this->load->view('home');
        $this->load->view('templates/footer');
    }

    public function panel()
    {
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->view('templates/header');
        $this->load->view('panel');
        $this->load->view('templates/footer');
    }
}   

and heres my routes (config/routes.php)

$route['main/index'] = "main/index";
$route['main/panel'] = "main/panel";
$route['default_controller'] = "main/index";

At first run, it will automatically go to main/index, it works fine, but when i click the panel link it says Object not found so does the Home link Object no found


Solution

  • First, you better have path relative to root in href:

       <a href="/main/index"> Home </a>
       <a href="/main/panel"> Panel </a>
    

    or, even better like this:

       <a href="<?=$base_url;?>main/index"> Home </a>
       <a href="<?=$base_url;?>main/panel"> Panel </a>
    

    next thing is views you are loading, correct way is to load one view in controller function:

       $this->load->view('home');
    

    and in home.php you need to include your other views, home.php:

       <?php $this->load->view('templates/header');?>
       ...
       <!--YOUR HOME HTML GOES HERE-->
       ...
       <?php $this->load->view('templates/footer');?>
    

    Now the routing. Be sure to use /index.php/[controller]/[function] links (unless you are using url rewrite like here http://ellislab.com/codeigniter/forums/viewthread/180566/)

    Routing config:

       $route['default_controller'] = "main/index"; //this is the only thing you need to define
    

    After all your pages will be accessible via such urls:

    Index page: http://example.com/ , http://example.com/index.php/main/index

    Panel page: http://example.com/index.php/main/panel