1

When creating routes for your MVC web application I have seen two possible ways to pass variables to a controller method:

With the first approach the variable is passed to a parameter of the controller method and utilized as such:

1a. http://domain.com/controller1/method1/variable1

1b. class controller1 extends main_controller(){

      function method1($var1){

         echo $var1; //prints "variable1"

      }

    }

The next approach uses URI parameters and allows for the name of the variables being passed to appear in the URL:

2a. http://domain.com/controller1/method1/variable1/34/variable2/56

2b. class controller1 extends main_controller(){

        function method1(){

            //split the uri into an array using framework function
            $uri = $this->uri_to_assoc()

            //call the uri variables as array indexes
            echo $uri['variable1']; //prints "34"

            echo $uri['variable2']; //prints "56"

        }         

    }

My question is concerning when to use one case vs the other? My guess would be that approach #2 would be more for RESTful web services while approach #1 would be for a web application that will be serving html and crawled by search engines?

2
  • 1
    If in the second method http://example.com/controller/method/var1/34/var2/56 and http://example.com/controller/method/var2/56/var1/34 access the same resource, then that breaks the URI idempotency. That can have a ignificant effect on clients. Commented Jan 21, 2015 at 18:34
  • The obvious choice is left out: query parameters. If the controller parameters aren't a part of the resource's proper name, they shouldn't appear in the path.
    – outis
    Commented Jun 23, 2015 at 1:02

1 Answer 1

0

I would say it depends on your needs.

  • Do you need to know the name of the variable?
  • Do you want the (multiple) variables to be passed in a specific order?
  • Is the amount of variables going to grow (like filters)?
  • Does it need to be part of the url? (i.e. for SEO reasons)

I mostly know two variants (different then the examples you gave), and in applications I write I catch these in these ways:

1. In the url: www.youtube.com/brandname

Using a regular expression I predefine the names of the different parts in the url. And thus their position is (mostly) fixed.

/(?<id>[0-9])/(?<slug>[a-z0-9])/

Then you can pass these named or unnamed to the controller. How doesn't matter that much, as you already know which are coming in already.

function channel($id, $slug)

2. In the GET/POST request: www.google.com/?q=foo&client=bar&channel=baz&...

Just accessing the GET/POST directly.

function search() {
    if (empty($_GET['q']) || invalid($_GET['q'])) {
        // return to user
    }

    $query = $_GET['q'];
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.