Question

I keep thinking about how to deal with URLs and pages with CI but I can't think to a good way to do this.

I'm trying to handle url like this:

site.com/shop (shop is my controller)
site.com/shop/3 (page 3)
site.com/shop/cat/4 (categorie and page 4)
site.com/shop/cat/subcat/3 (cat & subcat & page)

Is there any good way to do this ?

Was it helpful?

Solution

You could create controller functions to handle:

  • shop and shop pages
  • categories and category pages
  • subcategories and subcategory pages

Controller functions

In your shop controller you could have the following functions:

function index($page = NULL)
{
    if ($page === NULL)
    {
        //load default shop page
    }
    else  //check if $page is number (valid parameter)
    {
        //load shop page supplied as parameter
    }
}

function category($category = NULL, $page = 1)
{
    //$page is page number to be displayed, default 1
    //don't trust the values in the URL, so validate them
}

function subcategory($category = NULL, $subcategory = NULL, $page = 1)
{
    //$page is page number to be displayed, default 1
    //don't trust the values in the URL, so validate them
}

Routing

You could then setup the following routes in application/config/routes.php. These routes will map the URLs to the appropriate controller functions. The regex will allow look for values

//you may want to change the regex, depending on what category values are allowed

//Example: site.com/shop/1    
$route['shop/(:num)'] = "shop/index/$1";   

//Example: site.com/shop/electronics  
$route['shop/([a-z]+)'] = "shop/category/$1";

//Example: site.com/shop/electronics/2 
$route['shop/([a-z]+)/(:num)'] = "shop/category/$1/$2";

//Example: site.com/shop/electronics/computers
$route['shop/([a-z]+)/([a-z]+)'] = "shop/subcategory/$1/$2";

//Example: site.com/shop/electronics/computers/4 
$route['shop/([a-z]+)/([a-z]+)/(:num)'] = "shop/subcategory/$1/$2/$3";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top