Search code examples
phprestler

Can I pass a dictionary object to Restler?


I know I can specify 'array' as the type for arrays, but what do I use when I want to pass in a dictionary type to a method using Restler 3?

The whole 'outer' block passed to the POST method is of course a dictionary type, but now I want one of the parameters to be a dictionary type as well.


Solution

  • Dictionary in Request

    Define a dictionary as a class with public properties

    class Object
    {
        public $property = 'value';
    
        /** 
         * @var string {@required false} 
         */
        public $optional = 'value';
    
        //add more properties here
    }
    

    Let your api method use it as one of its parameters

    class Api
    {
        public function method(Object $obj, $name)
        {
            //use $obj->property here
        }
    }
    

    Dictionary in Response

    You can use an associative array (array with string indexes) or an instance of stdClass for this purpose

    return array {
    
        'name' => 'Gargoyle'
        'object' => array {
            'property' => 'value'
        }
    
    };
    

    or

    $r = new stdClass();
    $r->name = 'Gargoyle';
    $r->object = new stdClass();
    $r->object->property = 'value';
    return $r;
    

    Both result in an JSON object output