Search code examples
restler

Restler class with required params based on method type


Let's say I have this to use with my API classes

class EventInfo {
    /// @var int $start The Start time
    public $start

    /// @var string $url The URL for the event {@required false}
    public $url = null;
}

And now I want to use EventInfo for both my POST and my PATCH methods. When I'm doing a POST, $start is a required property to be set. The $url will come in as an optional parameter.

However, when I'm doing a PATCH operation, then $start should no longer be required. I might be passing a new start time, but I might not.

How do I specify this?


Solution

  • First, use the DocBlock syntax

    class EventInfo {
        /**
         * @var int $start The Start time
         */
        public $start;
    
        /**
         * @var string $url The URL for the event {@required false}
         */
        public $url = null;
    }
    

    This sets the default required and optional properties. Then you can control the required properties at api method level using {@required } comment. See the example below

    class Home
    {
        public function index()
        {
            return array(
                'success' => array(
                    'code' => 200,
                    'message' => 'Restler is up and running!',
                ),
            );
        }
    
        public function patch(EventInfo $info)
        {
            return func_get_args();
        }
    
        /**
         * @param EventInfo $info {@required start,url}
         * @return array
         */
        public function post(EventInfo $info)
        {
            return func_get_args();
        }
    }
    

    You may also add {@properties start} comment similarly to restrict which properties are needed by the API method.