views:

101

answers:

2

I use redirect() (from uri helper) in every function who need to load the main view of my app. It redirect to the same function. My goal is to get the same clean uri, even when i use a pages' feature (that call other controller). Is it good practice? When should i use redirect()? Are there any other solution to get a similar result?

this is some code to clarify.

Here is a controller :

<?php

   class Main_controller extends Controller
   {
       function index()
       {
       $this->load->view(page); 
       }

       function page_feature()
       {
       /* some stuff */
       redirect('main_controller.php','refresh');
       }
   }

With this route rules :

$route['([a-z-A-Z1-9_]+)'] = "main_controller";

The uri is like this : myapp.com/something On this page, there are feature who calls (on submit) other functions of main_controller ( or other controller), like a form for example:

<form action="myapp.com/another_controller/method" method="post">

at the end of this query "/another_controller/method", i use redirect('main_controller') to display the view with the new data, and keep the uri "myapp.com/something" instead of "myapp.com/another_controller/method".

I wanted to know if this is good or bad practice, and why.

+1  A: 

Redirection is most useful to prevent users from resubmitting form data. If you just display your output at the same URL you submit to, users refreshing the page will always get a prompt asking them to resubmit the form.

Redirecting also impacts the performance by making the client perform one more request to the server, but that's probably negligible in most situations.

Reinis I.
+3  A: 

It's bad practice to use redirects like that; you're basically doubling the # of server requests.

If you don't want to have the function names in the URL, just have the form POST to the controller index() function, and call the function you need based on some criteria such as what was passed from the forms POST data:

<form action="myapp.com/controller_name" method="post">

Controller:

function index(){
        if(!empty($_POST['some_form_data'])){
            $this->page_feature(); 
       }
       else{
            $this->load->view('page');
        }
}
function page_feature(){
       /* some stuff */
       $this->load->view('page_feature');
}

You may also want to check out the _remap() function. That way additional uri segments are not treated as function calls.

Mitchell McKenna
Thanks, it is what i was looking for.
Joeyjoejoe