php - CodeIgniter 动态 URI 路由可能吗?

标签 php codeigniter routing uri

我的应用程序旨在为每个用户提供一个个人资料页面,第三部分是用户的 ID。

example.com/profile/page/1

假设用户 1 是“Jon Jovi”,我想使用 CI 的路由生成这个 URI

example.com/jon_jovi

是否可以将此用户的 ID 发送到 config/routes.php,运行一个函数从数据库中提取用户 1 的信息并将其插入

$route['profile/page/$row->id'] = $row->first_name . '_' . $row->last_name;

非常感谢任何有关如何执行此操作的想法或建议 - 谢谢。

最佳答案

完全不确定这是否需要在您的 config/routes.php 中:您为什么不创建一个采用名称并进行查找的 Controller ?

编辑:我收回它。这实际上有点痛苦,特别是因为您希望它位于域的根目录(即,example.com/p/{username} 很容易做到,但是example.com/{username} 很乱。

最简单的方法是使用 CodeIgniter 2.0+ 覆盖 404 处理程序和 _remap 函数的能力。首先,在 config/routes.php 文件中执行此操作:

$route['404_override'] = 'notfound';

然后创建 Controller :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class NotFound extends CI_Controller
{
  function __construct()
  {
    parent::__construct();
  }

  public function _remap($method)
  {
    if($this->uri->total_segments() == 1){
      // try it out
      $this->profile();
    }else{
      show_404($this->uri->uri_string());
    }
  }

  function profile()
  {
    echo "Showing profile for [" . $this->uri->segment(1) . "]";
  }
}

您必须为 404 页面实现一个 View ,因为这会覆盖它,但任何未映射到现有 Controller 的请求都会进入此处,您可以根据需要分派(dispatch)它们,包括将名称转换为数据库 ID .

让我知道这是否适合您。

关于php - CodeIgniter 动态 URI 路由可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6222764/

相关文章:

php - Codeigniter 从 HTML 电子邮件中剥离字符

php - 使用 join codeigniter 进行求和查询

codeigniter - 没有证书的 SSL

php - 如果其中一个字段为空 PHP,则不将记录加载到数组中

php - c2dm : how to receive the message in the device?(使用 PHP)

php - 工作时间跨越午夜

asp.net-core - 在 Visual Studio blazor 项目中设置起始路线

php - 使用PHP在mysql中插入POST数据

routing - 找不到 Symfony 3 路由

networking - 两台计算机如何通过 NAT 连接到同一个外部地址?