6

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

4

2 回答 2

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');
    }
}

然后在您的自定义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);
    }
}
于 2012-11-29T09:37:44.323 回答
3

由于这个问题在谷歌搜索中仍然排名很高,我会注意到现在已经过了几年,Silex 添加了一个处理程序方法OPTIONS

http://silex.sensiolabs.org/doc/usage.html#other-methods

当前可以直接用作函数调用的动词列表是:get, post, put, delete, patch, options. 所以:

$app->options('/blog/{id}', function($id) {
  // ...
});

应该工作得很好。

于 2016-03-03T17:09:07.193 回答