ihymk 发表于 2010-5-22 10:38:56

关于单控制器路由处理

本帖最后由 ihymk 于 2010-5-22 15:05 编辑

先说明一下我的意图:
我是希望,用户看到的所有的URL,都通过一个统一的controller获取操作,这个controller可以说是一个工厂,处理这个url下的model输出,view显示;
首次的解决方法,直接将routes.php配置文件中添加
$route['(.*)'] = "index/index/$1";

前期使用还可以,后期,突然想,部分url还是用自己的controller处理,只对不存在的url定向到index,这样做看来不了行了。 于是,做了下面的改动 。
去掉routes.php中的路由。
扩展Router类:EA_Router.php
<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* 路由扩展控制
*=============================================================
* 版权所有: (c) eatools.cn Able Gao 保留所有权利
* 网站地址: http://www.eatools.cn
*=============================================================
* $Version:
* $Create : 10:25 2010/5/22 Able Gao <ablegao@gmail.com>
* $Edit   : 10:25 2010/5/22
* $File   : EA_Router.php
*/


class EA_Router extends CI_Router {
    var $suffix = '_controller';
    function MY_Router() {
      parent::CI_Router();
    }
    /**
* 控制器获取扩展,当控制器不存在时,跳转到默认控制器
* the controller.
*
* @access private
* @param array
* @return array
*/
function _validate_request($segments)
{

// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments.EXT))
{
   return $segments;
}

// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments))
{
   // Set the directory and remove it from the segment array
   $this->set_directory($segments);
   $segments = array_slice($segments, 1);
   
   if (count($segments) > 0)
   {
    // Does the requested controller exist in the sub-folder?
    if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments.EXT))
    {
   
   show_404($this->fetch_directory().$segments);
    }
   }
   else
   {
    $this->set_class($this->default_controller);
    $this->set_method('index');
   
    // Does the default controller exist in the sub-folder?
    if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
    {
   $this->directory = '';
   return array();
    }
   
   }
   return $segments;
}
// Can't find the requested controller...
return array('index','index');
//show_404($segments);
}
}
?>


我的改动并不大, 只是把最后输出show_404的位置去掉了,换成了return array('index','index')
这样,找不到controller的url会执行index/index 。
此后,你可以在index/index 判断什么时候抛出页面404错误了。但这么做成熟不成熟,不大清楚,有达人看看还有没有更好的解决办法,一起讨论一下。
页: [1]
查看完整版本: 关于单控制器路由处理