tags:

views:

48

answers:

2

This is maybe a simple syntax question or possibly a best-practices question in terms of codeigniter.

I should start by saying I'm not a PHP or Codeigniter person so trying to get up to speed on helping on a project.

I've found the CI documentation fairly good. The one question I can't find an answer to is how to make part of a URL optional. An example the CI documentation uses is this:

example.com/index.php/products/shoes/sandals/123

and then the function used to parse the URI:

function shoes($sandals, $id)

For my example, I'd like to be able to modify the URL as such:

example.com/index.php/products/shoes/all

So, if no ID is passed, it's just ignored. Can that be done? Should that be done?

A second question unrelated to my problem but pertaining to the example above, why would the variable $sandals be used as in the example, the value is 'sandals'? Shouldn't that variable be something like $shoetype?

A: 

You can do that easily, by setting a default value, as follows:

function shoes($type = 'all', $id = null)
{
   //assume the default type of shows: all
   //assume no ID (and do whatever behaviour - e.g. top 5 in that type)
}

Note that I believe you must specify those on the left to specify some on the right. You can't have an optional first segment and a required rightmost one.

Kurucu
That was it! Thanks!
DA
+1  A: 

There is two ways how you can do it...

function shoes($type = "all", $id = false)
{
    if ($type == "all")
    {

       // ... here you can show all

    } 
    else if (is_int($id))
    {

       // ...

    }
}

second way...

function shoes()
{
    $type = $this->uri->segment(3, 'all');
    $id = $this->uri->segment(4, false);

    // ... everything else can be same like first example

}
boki
Thanks for that additional info, boki!
DA