如何在CodeIgniter中实现动态控制器,消除重复控制器文件?
嘿,完全可以实现!你只需要结合CodeIgniter的路由规则和一个通用控制器,就能彻底消除这些重复的控制器文件,具体操作步骤如下:
1. 配置路由规则
打开application/config/routes.php,添加以下路由规则,把所有以Sf_开头的URL请求都映射到同一个通用控制器:
// 匹配不带方法的URL(比如 http://localhost/Sf_client/) $route['Sf_(:any)'] = 'Sf_resource/index/$1'; // 匹配带方法的URL(比如 http://localhost/Sf_client/list) $route['Sf_(:any)/(:any)'] = 'Sf_resource/$2/$1'; // 如果你的控制器还有带参数的方法,可以继续扩展路由,比如: // $route['Sf_(:any)/(:any)/(:num)'] = 'Sf_resource/$2/$1/$3';
这些规则的作用是:把Sf_client、Sf_network这类请求中的client、network提取出来,作为参数传递给Sf_resource控制器的对应方法。
2. 创建通用控制器
Sf_resource.php 删除原来的Sf_client.php、Sf_network.php等文件,新建一个Sf_resource.php控制器,代码如下:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sf_resource extends UTF_Controller { private $resource_subtype; function __construct() { parent::__construct(); // 这里可以做一些公共初始化操作,比如加载通用模型、库等 } // 处理默认访问(比如 http://localhost/Sf_client/) public function index($subtype) { // 统一转小写,避免大小写问题 $this->resource_subtype = strtolower($subtype); // 默认跳转到list方法,和原来的行为保持一致 $this->list($subtype); } // 列表方法,对应原来的list方法 public function list($subtype) { $this->resource_subtype = strtolower($subtype); // 根据subtype动态生成页面标题 $data['page_title'] = ucfirst($subtype) . ' list'; $this->template->set_title('CTL - '.$data['page_title']); // 如果你的视图需要用到resource_subtype,也可以把它传入$data $data['resource_subtype'] = $this->resource_subtype; $this->template->build('resources/list',$data); } // 如果原来的控制器还有其他方法,比如edit、delete,直接在这里添加即可 // 示例: // public function edit($subtype, $id) { // $this->resource_subtype = strtolower($subtype); // // 这里写编辑逻辑,和原来的代码一致,只是用$this->resource_subtype代替固定值 // } }
3. 验证效果
现在访问原来的URL(比如http://localhost/Sf_client/或http://localhost/Sf_network/list),都会自动路由到Sf_resource控制器,并且动态设置$this->resource_subtype的值,和原来多个控制器的效果完全一致。
额外提示
- 如果你的视图
resources/list需要根据不同的resource_subtype显示不同内容,直接在视图中使用$resource_subtype变量即可,不用修改视图结构。 - 后续新增类似的资源类型(比如
Sf_device),不需要新建控制器,直接访问http://localhost/Sf_device/即可,只要确保视图逻辑兼容就行。
内容的提问来源于stack exchange,提问作者kalaiyarasi M
相关产品推荐
相关产品推荐

