CodeIgniter dynamic URI routing possible?

核能气质少年 提交于 2019-12-03 21:15:06

If you want to the "client" url to be in format base_url/[username], you will probrably need to grab the username some regex routing, like $route['([a-zA-z_]+)'] = "profile/page/$1";, and look on your database for that user.

Another solution would be appending the id to the url, like base_url/[username]/[id]. For this, the regex $route['([a-zA-z_]+)/([0-9+])'] = "profile/page/$2"; would pass the id as the first parameter for the page function of Profile controller.

Check the Documentation for more details on dynamic routing: http://codeigniter.com/user_guide/general/routing.html

Not sure this needs to be in your config/routes.php at all: why don't you just create a controller that takes the name and does the lookup?

EDIT: I take it back. This is actually kinda painful to do, particularly because you want it to live on the root of the domain (i.e. it would be easy to to do example.com/p/{username}, but example.com/{username} is messy).

Easiest way to do this is to use CodeIgniter 2.0+'s ability to override the 404 handler and the _remap function. First, do this in the config/routes.php file:

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

Then create the 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) . "]";
  }
}

You have to implement a view for the 404 page as this overrides it, but any requests that don't map to an existing controller come in here and you can dispatch them however you want, including translating the name into a db ID.

Let me know if that works for you.

Sean Walsh

There was a similar question to this a few weeks ago. I have copy-pasted the relevant part of my answer below:

You'll want to extend CI's router and on an incoming request query the DB for the list of company names. If the URI segment matches a company name, you'll want to serve it up using your company/profile method. If it does not, you will ignore it and let CI handle it normally. Check out this post on this topic for more information: forum link.

In this case, just swap out "company" and "company/profile" for "username" and "profile/page" to make it relevant to your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!