【问题标题】:Restler 3 - Default value for a parameter blocks ability to pass parameter inRestler 3 - 参数的默认值阻止了传递参数的能力
【发布时间】:2012-10-10 10:50:38
【问题描述】:

我有一个非常简单的类,它源自 Restler 网站上给出的示例“Say”类​​。如下:

 <?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.";
  }
}

因为“hi”函数没有 $to 变量的默认值,所以它在很大程度上可以正常工作:

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

返回

嗨,杰克!

太好了。问题是当你有一个像“hello”或“nothing”函数这样的默认值时,你似乎不能再传递参数了:

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

任何帮助将不胜感激。

另外,我还注意到,如果您不使用带有“hi”的参数(这需要将 $ 设置为某个值),它也会返回 404 错误。我不确定这是否是预期的行为,但对于此类错误,这似乎是错误的错误消息。

【问题讨论】:

    标签: php restler


    【解决方案1】:

    Restler 2 的工作方式与您的预期完全一样,对于上述 hello 方法,它会生成以下路由

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

    但 Restler 3 只做一条路线

    GET say/hello   ⇠ Say::hello()
    

    这是因为智能路由,我们没有将可选参数映射到 url,所以可选参数可以作为查询字符串传递

    在 hi 方法的情况下,Restler 2 将其路由为

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

    作为 Restler 3 在哪里

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

    因此使say/hi 因缺少所需参数而失败

    这样做的原因是为了避免歧义。在routing example

    中有解释

    如果您希望 Restler 3 中所有 API 的 Restler 2 行为,请将以下内容添加到 index.php

    Defaults::$smartAutoRouting = false;
    

    如果你只是想在方法级别或类级别关闭智能自动路由,添加以下 php doc 注释

    @smart-auto-routing false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-20
      • 2015-10-30
      • 2016-01-02
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多