2

I'm building a tutorialsystem with codeigniter and would like to achieve the following URL structure:

  • /tutorials --> an introduction page with the list of all the categories
  • /tutorials/{a category as string} --> this will give a list of tutorials for the given category, e.g. /tutorials/php
  • /tutorials/{a category as string}/{an ID}/{tutorial slug} --> this will show the tutorial, e.g. /tutorials/php/123/how-to-use-functions
  • /tutorials/add --> page to add a new tutorial

The problem is that when I want to use the first two types of URLs, I'd need to pass parameters to the index function of the controller. The first parameter is the optional category, the second is the optional tutorial ID. I've did some research before I posted, so I found out that I could add a route like tutorials/(:any), but the problem is that this route would pass add as a parameter too when using the last URL (/tutorials/add).

Any ideas how I can make this happen?

3 Answers 3

14

Your routing rules could be in this order:

$route['tutorials/add'] = "tutorials/add"; //assuming you have an add() method
$route['tutorials/(:any)'] = "tutorials/index"; //this will comply with anything which is not tutorials/add

Then in your controller's index() method you should be able to work out whether it's the category or tutorial ID is being passed!

Sign up to request clarification or add additional context in comments.

1 Comment

this has a problem for SEO purposes.
10

I do think that a remap must be of more use to your problem in case you want to add more methods to your controller, not just 'add'. This should do the task:

function _remap($method)
{
  if (method_exists($this, $method))
  {
    $this->$method();
  }
  else {
    $this->index($method);
  }
}

Comments

3

A few minutes after posting, I think I've found a possible solution for this. (Shame on me).

In pseudo code:

public function index($cat = FALSE, $id = FALSE)
{
    if($cat !== FALSE) {
        if($cat === 'add') {
            $this->add();
        } else {
            if($id !== FALSE) {
                // Fetch the tutorial
            } else {
                // Fetch the tutorials for category $cat
            }
        }
    } else {
        // Show the overview
    }
}

Feedback for this solution is welcome!

2 Comments

There are easier ways to achieve this in Codeigniter. Look at Aidas answer, that should do it.
Indeed, I'm still stuck in the old-fashioned way of working :$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.