• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Practical Examples Using URI Segments For URL's

I feel stupid for asking this, but I just can't find any practical examples of structuring a controller's functions to work with URI segments. Wouldn't this be better than routing them? Does anyone have any practical examples for using this very basic CI feature? I'm used to using plain old GET.

What specifically I'm after is creating a /controller/function/parameter url and working with it seemlessly in a "best practice" sort of way through the controller and views.

OK... so let's say I have a news controller... and I want to view a specific article...

So I create a news controller, with an article method, that takes one parameter.
class News extends Controller {
    function article ($articleID)
        $queryData = $this->gnome_news->get_article($articleID);
        $data['articleCount'] = count($queryData);
        $data['articles'] = $queryData;
        $this->load->view('news/news_article', $data);


Now my urls look like {base url}/news/article/123

Does that help?


To expand on the example:
class News extends Controller {

  // url: domain.tld/news
  // shows a list of news items with teasers
  function index() {}

  // url: domain.tld/news/sort/$sortby/$direction
  // shows a list of news items with teasers sorted a specific way for example date
  function sort($sortby, $direction = 'DESC') {}

  //url: domain.tld/news/article/$id
  // shows a specific news item plus full news content
  function article($id) {}

  //url: domain.tld/news/add
  // adds a news item
  function add() {}

  //url: domain.tld/news/edit/$id
  // edit a news item with specific $id
  function edit($id) {}

  //url: domain.tld/news/delete
  // delete a news item with specific $id using POST
  function delete() {}

Say there were multiple parameters, but I also want the function to take zero parameters... Is the best way to do that just setting the variables to false and checking for that?

rather than having parameters on the method, you can use the URI object to get the segments of the uri. this allows for a flexible number of parameters

$segments = $this->uri->uri_to_assoc(2);
produces an associate array of segments, which i prefer to just referencing as numbers (but that is a personal decision)
so the urls could be
{base url}/news/article/id/123/format/print
$segments would have the following

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.