【问题标题】:How to route cutom URL with to custom controller in CodeIgniter?如何将自定义 URL 路由到 CodeIgniter 中的自定义控制器?
【发布时间】:2014-09-28 09:22:06
【问题描述】:

我有一个名为 User 的 PHP CodeIgniter 控制器,并且有一个方法可以获取用户 user_detail($username) 的详细信息
现在,当我需要显示用户数据时,例如 userName mike
我称这个网址为
http://www.example.com/user/user_detail/mike

我的目标
如何使下一个 URL 可以访问用户数据
http://www.example.com/user/mike
或/和
http://www.example.com/mike

【问题讨论】:

    标签: php codeigniter uri url-routing


    【解决方案1】:

    你必须阅读codeigniter官方文档中的page。它轻松涵盖了与路由 URL 相关的所有内容。所有路由都必须通过文件配置:

    application/config/routes.php
    

    可能是这样的:

    $route['user/(:any)'] = "user/user_detail/$1";
    

    【讨论】:

    • $route['user/(:any)'] = "user/user_detail/$1"; $route['(:any)'] = "user/user_detail/$1";
    【解决方案2】:

    这可以通过覆盖CI_Controller 类来实现,但不要更改原始核心文件,就像我说的那样覆盖控制器并将您的逻辑放入其中。

    求助:https://ellislab.com/codeigniter/user-guide/general/core_classes.html

    how to create Codeigniter route that doesn't override the other controller routes?

    也许更简单的解决方案是借助 .htaccess 中的 apache mod_rewrite 对其进行路由

    这里详细解释了如何实现:http://www.web-and-development.com/codeigniter-remove-index-php-minimize-url/

    【讨论】:

      【解决方案3】:

      Hatem 的回答(使用路由配置)更简单、更简洁,但指出 _remap() 函数的用法在某些情况下可能会有所帮助:

      CI_Controller 中,_remap() 函数将在每次调用控制器时执行,以决定使用哪种方法。在那里你可以检查该方法是否存在,或者使用一些定义的方法。在你的情况下:

      application/controllers/User.php

      class User extends CI_Controller {
          public function _remap($method, $params = array())
          {
              if (method_exists(__CLASS__, $method)) {
                  $this->$method($params);
              } else {
                  array_unshift($params, $method);
                  $this->user_detail($params);
              }
          }
      
          public function user_detail($params) {
              $username = $params[0];
              echo 'username: ' . $username;
          }
      
          public function another_func() {
              echo "another function body!";
          }
      }
      

      这将导致:

      http://www.example.com/user/user_detail/john => '用户名:john' http://www.example.com/user/mike ...... => '用户名:迈克' http://www.example.com/user/another_func ... => '另一个函数体!'

      但它不适用于: http://www.example.com/mike ,因为控制器 - 即使它是默认控制器 - 根本不会被调用,在这种情况下,CI 默认行为是寻找一个名为 mike 的控制器,如果找不到它会抛出 404 错误。

      更多:

      Codeigniter userguide 3: Controllers: Remapping Method Calls

      Redirect to default method if CodeIgniter method doesn't exists.

      【讨论】:

        猜你喜欢
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多