Welcome Guest, Not a member yet? Register   Sign In
Need help understanding routes
#1

[eluser]hitraj47[/eluser]
I am new to CodeIgniter. I am making a fake CMS to learn it and I am trying to set up my routes. What I want to do is if someone goes to mysite.com/admin/add-page it will call the add_page() function of the Admin controller.

I have already made a routes file that automatically turns dashes in URL's to underscores, here is the code just to make sure I've written it correctly:

application/core/MY_Router.php
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Router extends CI_Router {

function __construct()
{
  parent::__construct();
}

public function _set_request($segments){
  
  for($i = 0; $i < count($segments); ++$i){
  
   if(isset($segments[$i])){
    
    $segments[$i] = str_replace('-', '_', $segments[$i]);
    
   }
  
  }
  
  // Run the original _set_request method, passing it our updated segments.
  parent::_set_request($segments);
  
}

}

Now in my config/routes.php I have:
Code:
$route['login'] = 'login';
$route['login/:any'] = 'login/$1';

$route['admin'] = 'admin';
$route['admin/:any'] = 'admin/$1';

$route['default_controller'] = 'page/view';
$route['(:any)'] = 'page/view/$1';
$route['404_override'] = 'page/error404';

I am not sure if you can tell what I am trying to do here, but I am trying to avoid making a route every time I add a method to a controller. So when I create the delete_page() method in Admin, the user will go to mysite.com/admin/delete-page and it will load the method.

It's not working right now because I get an error 404. However when I add:
Code:
$route['admin/add-page'] = 'admin/add_page';
to my routes file, it works fine.

Have I done this properly? Is this an accepted practice or is it better or even more secure to create a route for each function manually?
#2

[eluser]InsiteFX[/eluser]
The defaults must come first before any other routes!
Code:
$route['default_controller'] = 'page/view';
$route['404_override'] = 'page/error404';

$route['login'] = 'login';
$route['login/:any'] = 'login/$1';

$route['admin'] = 'admin';
$route['admin/:any'] = 'admin/$1';

$route['(:any)'] = 'page/view/$1';
#3

[eluser]CroNiX[/eluser]
Also, routes where you use a captured segment (like $1 below), you need to use (:any) instead of just :any
Code:
$route['login/:any'] = 'login/$1';
#4

[eluser]hitraj47[/eluser]
[quote author="InsiteFX" date="1337555184"]The defaults must come first before any other routes![/quote]

Thanks for the advice, I have rearranged my routes accordingly.

"Also, routes where you use a captured segment (like $1 below), you need to use (:any) instead of just :any"

This was what was causing the problem, it works now. Thanks!




Theme © iAndrew 2016 - Forum software by © MyBB