dongxueji2838 2014-04-30 11:15
浏览 39
已采纳

CodeIgniter自定义通用路由器类

I'm trying to "shorten" my URLs, for example from:

http://mydomain.com/controller/method/something-here

into

http://mydomain.com/something-here

by adding to routes.php:

$route['(.*)'] = 'router/resolve/$1';

and creating a Router class, whose resolve() method determines whether something-here matches a row in one of my database tables (entities). If so, I want to load the entry by calling the appropriate controller::method.

For example, if something-here is a type of book, I'd like Router::resolve() to call Book::view($id).

However, I realize it's not possible for a controller to call the method of another controller. (Is it?)

I also cannot use redirect("book/view/$id") because $route['(.*)'] will call Router::resolve() on book (the first segment).

Any suggestions on how to achieve my goal?

  • 写回答

1条回答 默认 最新

  • douzhi9395 2014-04-30 13:47
    关注

    I can think of two solutions;
    1) Use a HMVC architecture, which would allow for calling one controller from another.

    2) Dynamically generate your routes.
    This may not be the most efficient or elegant solution, but it is an option.

    <?php
    $route[ 'default_controller' ]  = 'main';
    $route[ '404_override' ]        = 'error404';
    
    require_once( BASEPATH .'database/DB'. EXT );
    $db =& DB();
    $query = $db->get( 'whatever_table' );
    $result = $query->result();
    foreach( $result as $row )
    {
        $route[$row->slug.'/(:any)'] = $row->controller.'/'.$row->method.'/$1';
    }
    

    As it has been pointed out to me before, routes are processed using a regex (in _parse_routes) so this may not be the quickest in performance, it depends on how many routes you would be generating and how you feel about the performance impact.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解