Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silex - OPTIONS method

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?

like image 281
Peter Krejci Avatar asked Nov 29 '12 09:11

Peter Krejci


2 Answers

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);
    }
}
like image 77
gremo Avatar answered Sep 22 '22 06:09

gremo


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.

like image 3
MidnightLightning Avatar answered Sep 22 '22 06:09

MidnightLightning