简体   繁体   中英

Rename url from DB in Codeigniter

I made a website that contains products with the url: http://somesite.com/controller/function/brand_id/product_id . I would want to change those ID's to more search friendly names. All those ID are in the DB with a name. Is it possible to get those names out of the DB and put them in the URL? This because i can't use the routing tool. The products and brands are dynamically and could be deleted or (name) changed at any time. So can't hardcode this into the routes.

Thanks for the effort

You can use several functions in your url using _remap Codeigniter built-in function: Use the following function inside your controller:

public function _remap($method){
if ($method == 'project-name')
{
   //display project1
}
elseif($method == 'project-name2')
{
   //display project2
}

Another example using params:

public function _remap($method, $params = array())
{
    $method = 'process_'.$method;
    if (method_exists($this, $method))
    {
        return call_user_func_array(array($this, $method), $params);
    }
    show_404();
}

$method is the function in your Url: http://somesite.com/controller/function/brand_id/product_id

You can do the same for varying methods by extracting them from database

take a look here: http://codeigniter.com/user_guide/general/controllers.html#remapping

You should be able to accomplish this by setting up some wildcard routes for brand_id and product_id . When you are performing the query for the product, you can just check to see if the URI segments are integers (IDs) or strings (names) and query the DB accordingly. I would store a URL-friendly version of the product name (replace spaces and special chars) and then query that, and also use that for generating links throughout the app.

Update: Here is a code sample for the logic you would want in the method that you are routing everything through:

public function search($brand, $product)
{
    if (is_int($brand))
    {
        // Look up the brand using an ID
        $this->db->where('id', $brand);
    }
    else
    {
        // Look up the brand based on the URI segment
        $this->db->where('uri_friendly_name', $brand);
    }

    // Do the same with adding conditionals for $product and then run the query
}

and here is an example of the route you would need:

$route['controller/function/(:any)/(:any)'] = "controller/search";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM