用户
 找回密码
 入住 CI 中国社区
搜索
查看: 8441|回复: 9
收起左侧

[控制器] 不带/index/实现给控制器的index()传参数?(我的方法+问题)

[复制链接]
发表于 2010-7-26 23:13:47 | 显示全部楼层 |阅读模式
以CMS做例子吧,先不说实现合不合理,假定我的控制器是Category
那么列出分类的理想URI应该是:http://localhost/category/categoryname
但是很显然根据CI的URI格式,categoryname那里是函数名的地方
也就是说想让categoryname变成参数,我必须http://localhost/category/index/categoryname

我希望在控制器没有对应函数的时候,categoryname能作为index()函数的一个参数传入,实现缩掉index

我用URI路由实现的方法如下:
PHP复制代码
class Category extends Controller
{
function _remap($method)
{
  if (method_exists($this, $method))
    {$this->$method();}
  else
    {$this->index($method);}
}
 
function index($category='') //必须带默认值
{
  ... ...
}
... ...
复制代码


我现在弄不清楚的问题是:
1. 我希望对整个程序中所有的控制器都应用这个路由规则该怎么做?(一个一个插当然不科学)
2. 如果URL中有多个参数会怎么样?
3. 会因为特殊字符造成安全性问题吗?
发表于 2010-7-26 23:29:20 | 显示全部楼层
理论上 MY_Controller 可以解决楼主的问题,但我没试过 _remap 方法。
发表于 2010-7-27 08:35:29 | 显示全部楼层
配置个uri路由
$route['category/(:any)'] = 'category/index/$1';
发表于 2010-7-27 09:57:42 | 显示全部楼层
本帖最后由 ares333 于 2010-12-9 17:32 编辑

MY_Controller应该可以,不过还有更好的方法,只不过要对正则有一定了解才好.给你一个终极解决方法,绝对强悍
http://codehere.net/codeigniter-url.html
发表于 2010-8-3 11:13:02 | 显示全部楼层
学习了,呵呵
发表于 2010-9-14 12:01:59 | 显示全部楼层
CI正常的URL应该是http://www.xxx.com/index.php/kongzhiqi/index/canshu
直接用.htaccess 将中间的 index.php/kongzhiqi/index 省略掉,直接变成 http://ww.xxx.com/canshu。我是这样做的。
发表于 2012-1-12 11:43:08 | 显示全部楼层
ici 发表于 2010-7-27 08:35
配置个uri路由
$route['category/(:any)'] = 'category/index/$1';

强烈同意,最方便的一种方法。
发表于 2013-6-23 10:43:17 | 显示全部楼层
//我这么写,就可以随便多少参数
public function _remap($method, $params = array()){
                if (method_exists($this, $method)){
                        return call_user_func_array(array($this, $method), $params);
                }else{
                        //如果没有方法,则把$method压入第一个参数
                        $arr1stParam = array($method);
                        $params = array_merge($arr1stParam,$params);
                        call_user_func_array(array($this, 'index'), $params);
                }
        }
发表于 2013-8-1 17:23:38 | 显示全部楼层
ici 发表于 2010-7-27 08:35
配置个uri路由
$route['category/(:any)'] = 'category/index/$1';

赞,我就是这么搞得~
发表于 2016-11-1 23:00:37 | 显示全部楼层
把8楼的代码直接复制到/system/core/Controller.php类中即可,已测试.

本版积分规则