开发者

Optional URL fragment in Codeigniter?

开发者 https://www.devze.com 2023-01-02 22:23 出处:网络
This is maybe a simple syntax question or possibly a best-practices question in terms of codeigniter.

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?


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.


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消