Silex - OPTIONS method
Asked Answered
S

2

6

I'm using Silex framework for mocking REST server. I need to create uri for OPTIONS http method, but Application class offers only methods for PUT, GET, POST and DELETE. Is it possible to add and use a custom http method?

Summerwood answered 29/11, 2012 at 9:17 Comment(0)
L
4

I did the same thing but I can't remember very well how I managed to make it work. I can't try it right now. For sure you have to extend the 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');
    }
}

And then use it in your custom Application class:

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);
    }
}
Lebensraum answered 29/11, 2012 at 9:37 Comment(1)
Using $app->match($pattern, $to)->method('OPTIONS'); directly is easy enough.Aeroscope
H
3

Since this question still comes up highly-ranked in Google searches, I'll note that now that it's several years later, Silex added a handler method for OPTIONS

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

The current list of verbs that can be used as function calls directly are: get, post, put, delete, patch, options. So:

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

Should work just fine.

Hardtack answered 3/3, 2016 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.