【问题标题】:_remap or URI Routing in codeignitercodeigniter 中的 _remap 或 URI 路由
【发布时间】:2012-08-20 10:23:55
【问题描述】:

我目前正在研究 PHP 框架 Codeigniter 并了解到目前为止的主要概念,直到关于 _remapping 的控制器部分。我了解 _remapping 如何通过 URI 覆盖控制器方法的行为,例如从 www.example.com/about_me 到 www.example.com/about-me。我想听的是人们对使用什么的意见——_remapping 方法或 URI Routing 方法?我只是在研究这些方法时问这个问题,并且有人对重新映射功能感到困扰,他们被指示使用 URI 路由。

所以..

1) 主要的常用方法是什么,专业人士的使用方法是什么? 2) PHP5 CI 版本 2 以后最好使用 URI 路由吗?

很高兴听到您的意见!

【问题讨论】:

    标签: php codeigniter uri url-routing remap


    【解决方案1】:

    假设您不想使用Categories 控制器的index(即http://www.yourdomain.com/category)操作,您可以使用路由。

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

    然后,您只需在 Category 控制器中执行 View 操作即可接收 Category 名称,即 PHP。

    http://www.yourdomain.com/category/PHP

    function View($Tag)
    {
        var_dump($Tag);
    }
    

    如果您仍想在控制器中访问索引操作,您仍然可以通过http://www.yourdomain.com/category/index 访问它

    【讨论】:

      【解决方案2】:

      如果你想改变默认 CI 路由的行为,你应该使用 _remap。

      例如,如果您设置维护并希望阻止任何特定控制器运行,则可以使用 _remap() 函数加载您的视图,并且不会调用任何其他方法。

      另一个例子是当你的 URI 中有多个方法时。示例:

      site.com/category/PHP
      site.com/category/Javascript
      site.com/category/ActionScript
      

      您的控制器是category,但方法不受限制。 在那里,您可以使用 Colin Williams 在这里调用的 _remap 方法: http://codeigniter.com/forums/viewthread/135187/

       function _remap($method)
      {
        $param_offset = 2;
      
        // Default to index
        if ( ! method_exists($this, $method))
        {
          // We need one more param
          $param_offset = 1;
          $method = 'index';
        }
      
        // Since all we get is $method, load up everything else in the URI
        $params = array_slice($this->uri->rsegment_array(), $param_offset);
      
        // Call the determined method with all params
        call_user_func_array(array($this, $method), $params);
      }  
      

      综上所述,如果当前 CI 的路由适合你的项目,不要使用 _remap() 方法。

      【讨论】:

        【解决方案3】:
        $default_controller = "Home";
        
        $language_alias = array('gr','fr');
        
        $controller_exceptions = array('signup');
        
        $route['default_controller'] = $default_controller;
        
        $route["^(".implode('|', $language_alias).")/(".implode('|', $controller_exceptions).")(.*)"] = '$2';
        
        $route["^(".implode('|', $language_alias).")?/(.*)"] = $default_controller.'/$2';
        
        $route["^((?!\b".implode('\b|\b', $controller_exceptions)."\b).*)$"] = $default_controller.'/$1';
        
        foreach($language_alias as $language)
        
        $route[$language] = $default_controller.'/index';
        

        【讨论】:

        • 你能详细说明你的答案吗?发布一段没有任何文字的代码通常不是很有帮助。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 2013-06-19
        • 1970-01-01
        相关资源
        最近更新 更多