Search code examples
phprestsymfonysilexhttp-method

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?


Solution

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