编码点火器 如何为控制器类和方法设置路由


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

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

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

  • 首页.php
  • 报告.php

/视图/

  • 首页/索引.php
  • 首页/最近.php
  • 报告/索引.php
  • 报告/生成.php

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

http://localhosthttp://localhost/report(将加载索引.php)http://localhost/report/generate(将在报表控制器中调用 generate 方法)

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

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

如何避免总是修改类中创建的每个新方法的路由文件?以便它遵循:$route[$controller/$method/$variable](非常习惯如何设置.NET MVC路由)。

任何帮助,不胜感激。

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

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

这个也是多余的:

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

由于默认控制器设置为"home",并且默认方法始终index .

了解 CI 如何使用 URL:https://www.codeigniter.com/user_guide/general/urls.html

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

这条路线很好:

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

if 将获取 URL /localhost/recent/123并将加载Home、控制器recent方法,并将123作为第一个方法参数传递。