2

I am new to CI and need some beginner's help from experts.

Here is what my current setup is: /controllers/

  • home.php
  • report.php

/views/

  • home/index.php
  • home/recent.php
  • report/index.php
  • report/generate.php

the URI i am trying to produce as an outcome:

http://localhost http://localhost/report (would load the index.php) http://localhost/report/generate (would call the method for generate in the report controller)

http://localhost/recent/10 (would call the method for generate in the home controller passing the variable '10')

$route['default_controller'] = "home";
$route['404_override'] = '';
$route['/'] = 'home/index';
$route['recent/(:num)'] = 'home/recent/$1';
$route['report/(:any)'] = 'report/$1';

How do i avoid always modifying the routes file for each new method created in a class? so that it would follow: $route[$controller/$method/$variable] (very use to how .net mvc routing is setup).

Any help is appreciated.

Rick
  • 555
  • 1
  • 12
  • 30

1 Answers1

10

You don't need further modifications. In fact, even this line is redundant:

$route['report/(:any)'] = 'report/$1';

This one is also redundant:

$route['/'] = 'home/index';

since the default controller is set to 'home' and the default method is always index.

Look at how CI works with URLs: https://www.codeigniter.com/user_guide/general/urls.html

So, /localhost/report/generate would look for the Report controller, and load its generate method. That's how it works out-of-the-box, no routing needed.

And this route is fine:

$route['recent/(:num)'] = 'home/recent/$1';

If will take the URL /localhost/recent/123 and will load the Home, controller, recent method and will pass 123 as the first method parameter.

Stack Programmer
  • 679
  • 6
  • 18
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • Thanks shomz, but I am getting a 404 error: The requested URL /recent/10 was not found on this server. [edit] seems like this works fine: http://localhost/index.php/recent/10... how do i ignore or exclude the index.php in the URL? – Rick Feb 03 '15 at 00:51
  • You're welcome. It's described in the URL I gave you in my answer, and there are many answers here, like this one: http://stackoverflow.com/questions/19183311/codeigniter-removing-index-php-from-url – Shomz Feb 03 '15 at 01:27
  • 1
    Thank you for pointing me into the right direction. The htaccess update made the difference. – Rick Feb 03 '15 at 01:30