Silex - OPTIONS方法

Pet*_*jci 6 php rest http-method symfony silex

我正在使用Silex框架来模拟REST服务器.我需要为OPTIONS http方法创建uri,但是Application类只提供PUT,GET,POST和DELETE的方法.是否可以添加和使用自定义http方法?

gre*_*emo 4

我做了同样的事情,但我不太记得我是如何让它发挥作用的。我现在无法尝试。当然你必须扩展ControllerCollection

class MyControllerCollection extends ControllerCollection
{
    /**
     * Maps an OPTIONS request to a callable.
     *
     * @param string $pattern Matched route pattern
     * @param mixed  $to      Callback that returns the response when matched
     *
     * @return Controller
     */
    public function options($pattern, $to)
    {
        return $this->match($pattern, $to)->method('OPTIONS');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的自定义Application类中使用它:

class MyApplication extends Application
{
    public function __construct()
    {
        parent::__construct();

        $app = $this;

        $this['controllers_factory'] = function () use ($app) {
            return new MyControllerCollection($app['route_factory']);
        };
    }

    /**
     * Maps an OPTIONS request to a callable.
     *
     * @param string $pattern Matched route pattern
     * @param mixed  $to      Callback that returns the response when matched
     *
     * @return Controller
     */
    public function options($pattern, $to)
    {
        return $this['controllers']->options($pattern, $to);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 直接使用 `$app->match($pattern, $to)->method('OPTIONS');` 就足够简单了。 (6认同)