codeigniter 如何为控制器 class 和方法设置路由?

codeigniter how do i setup routing for controller class and method?

我是 CI 的新手,需要专家的一些初学者帮助。

这是我当前的设置: /控制器/

/浏览量/

我尝试生成的 URI 作为结果:

http://localhost http://localhost/report(将加载 index.php) http://localhost/report/generate(会在报表控制器中调用生成方法)

http://localhost/recent/10(将在传递变量“10”的家庭控制器中调用生成方法)

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

如何避免总是为 class 中创建的每个新方法修改路由文件?这样它就会遵循: $route[$controller/$method/$variable](非常适用于如何设置 .net mvc 路由)。

感谢任何帮助。

您不需要进一步修改。事实上,即使是这一行也是多余的:

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

这个也是多余的:

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

因为默认控制器设置为 'home' 并且默认方法是 always index.

看看 CI 如何与 URL 一起工作:https://www.codeigniter.com/user_guide/general/urls.html

因此,/localhost/report/generate 将查找 Report 控制器,并加载其 generate 方法。这就是它开箱即用的方式,不需要路由。

这条路线很好:

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

If 将采用 URL /localhost/recent/123 并将加载 Home、控制器、recent 方法并将传递 123 作为第一个方法参数.