【问题标题】:Silex - OPTIONS methodSilex - 选项方法
【发布时间】:2012-11-17 07:48:51
【问题描述】:

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

【问题讨论】:

    标签: php rest symfony silex http-method


    【解决方案1】:

    我也做过同样的事情,但我不太记得我是如何做到的。我现在不能尝试。当然你必须扩展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);
        }
    }
    

    【讨论】:

    • @PeterKrejci 很高兴听到这个消息 :)
    • 直接使用$app->match($pattern, $to)->method('OPTIONS');很简单。
    【解决方案2】:

    由于这个问题在 Google 搜索中的排名仍然很高,我会注意到,几年后,Silex 为OPTIONS 添加了一个处理程序方法

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

    目前可以直接用作函数调用的动词列表有:getpostputdeletepatchoptions。所以:

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

    应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多