Search code examples
phprestler

Restler 3 - Default value for a parameter blocks ability to pass parameter in


I have a very simple class that derives off of the example "Say" class given on the Restler website. It is as follows:

 <?php
class Say {
  function hello($to='world') {
    return "Hello $to!";
  }
  function hi($to) {
    return  "Hi $to!";
  }

  function nothing($to='the ground') {
    return "Looks at {$to} quietly but without saying a word.";
  }
}

Because the "hi" function does NOT have a default value for the $to variable it largely works as it should:

http://localhost/api/say/hi/Jack

returns

Hi Jack!

Great. The problem is when you have a default value like the "hello" or "nothing" functions then it seems you can't pass in the parameter anymore:

http://localhost/api/say/hello          -- WORKS, returns "Hello world!"
http://localhost/api/say/hello/Jack     -- FAILS, returns a JSON error of 404

Any help would be greatly appreciated.

On a side note, I also noticed that if you don't use a parameter with "hi" (which requires that $to be set to something) that it returns a 404 error as well. I'm not sure if that's expected behaviour but it seems like the wrong error message for this kind of error.


Solution

  • Restler 2 worked exactly like you expect, for the above hello method it generates the following routes

    GET say/hello      ⇠ Say::hello()
    GET say/hello/{to} ⇠ Say::hello()
    

    But Restler 3 only makes one route

    GET say/hello   ⇠ Say::hello()
    

    This is happening because of smart routing, where we do not map optional parameters to url, so optional parameters can be passed as a query string

    In the case of hi method Restler 2 routes it as

    GET say/hi      ⇠ Say::hi()
    GET say/hi/{to} ⇠ Say::hi()
    

    Where as Restler 3

    GET say/hi/{to} ⇠ Say::hi()
    

    Thus making say/hi to fail as the required parameter is missing

    Reason for doing this is to avoid ambiguity. It is explained here in the routing example

    If you want Restler 2 behaviour for all you API in Restler 3 add the following to index.php

    Defaults::$smartAutoRouting = false;
    

    If you just want to turn off smart auto routing at method level or class level, add the following php doc comment

    @smart-auto-routing false