CodeIgniter: Directing to functions with a URL segment


Question

I'm working on a survey system for my company and I have it setup in the system so that there are two ways to take the survey.

1) New Survey Taker no prior information

2)Survey was already sent out and a session was created.

In case one I would like my URL to look like:
mydomain.com/SurveySystem/index.php/survey/$surveyID

($surveyID being a integer of the survey to take)

The second case would where we create a link with for the test taker. I would like the URL to look like this:
mydomain.com/SurveySystem/index.php/survey/$surveySessionID/$guestID

In my Survey class I have it setup as the following:

function index(){

$segments = $this->uri->total_segments();

if($segments == 1){
   echo "no surveyID set";
   return;
}

if($segments == 2){
    $this->take_survey($this->uri->segment(2));
}

if($segments == 3){
    $this->survey_session($this->uri->segment(3), $this->uri->segment(4));
}

}

When no information is passed the it echos just fine. But if I try to put a integer where the surveyID is it thinks i'm loading up a method in the controller.

Thank you for the help!

1
1
7/9/2009 8:04:19 PM

Accepted Answer

Use URI routing to override the default controller/function/arguments mapping.

Example: in your application/config/routes.php:

$route['survey/:num'] = "survey/take_suvey";

Bonus: You can also remove the index.php/ part, see Removing the index.php file.

7
7/9/2009 8:08:58 PM

My question is, with a URL that unfriendly, why do you care what it looks like at all? It is not semantic from a user perspective. Yes, you should be removing the index.php. Coupling the URL rewriting, the whole thing should be reduced from:

mydomain.com/SurveySystem/index.php/survey/????

to

mydomain.com/survey/

And your CI class methods can be reduced to "take," or "submit," and a subsequent "review."

Sessions should be managed using cookies or CI's session class. If you need to track state in the URI, combine your survey-specific "session" and the "guestID" into one segment with base64 encoding.

Lastly, using a route as suggested, there will be no way for your app to know what survey ID to load. It would need to capture the ":num" and feed it to take_survey:

$route['survey/(:num)'] = "survey/take_survey/$1";

If you take numeric ids as the first segment after /survey, you need another route placed after that one to handle the case where that segment is a session ID:

$route['survey/(:num)/(:num)'] = "survey/session_manager/$1/$2";

Where the $1 and $2 are session ID and Guest ID respectively. Personally, I would say this is bad form. The semantic meaning of your segments break down: it becomes difficult to determine what that first numeric segment means (is it a survey ID or session ID), unless you can always guarantee that these routes are in place.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon