1

我有一个基本的服务描述模式来获取如下所示的用户模型:

{
    "name": "API",
    "baseUrl": "http://localhost/",
    "operations": {
        "GetUser": {
            "httpMethod": "GET",
            "uri": "users/{user_id}",
            "summary": "Show user details",
            "responseClass": "GetUserOutput",
            "parameters": {
                "user_id": {
                    "location": "uri",
                    "description": "ID of the user to be returned"
                 }
             }
         }
    },
    "models": {
        "User" : {
            "type": "object",
            "properties": {
                "id": {
                    "location": "json",
                    "type": "integer",
                    "sentAs": "user_id"
                 },
                "username": {
                     "location": "json",
                     "type": "string"
                 },
                "email": {
                    "location": "json",
                    "type": "string"
                }
            }
        },
       "GetUserOutput": {
            "$ref": "User"
        }
    }
}

我的客户执行以下操作:

require_once('../../vendor/autoload.php');

$client = new \Guzzle\Service\Client();
$client->setDescription(\Guzzle\Service\Description\ServiceDescription::factory(__DIR__ . '/client.json'));
$authPlugin = new \Guzzle\Plugin\CurlAuth\CurlAuthPlugin('23', '9bd2cb3f1bccc01c0c1091d7e88e51b208b3792b');

$client->addSubscriber($authPlugin);
$command = $client->getCommand('getUser', array('user_id' => 23));
$request = $command->prepare();
$request->addHeader('Accept', 'application/json');

try {
    $result = $command->execute();
    echo '<pre>' . print_r($result, true) . '</pre>';
}

它返回一个 Guzzle\Service\Resource\Model 对象,它在底部包含我想要的用户数据:

[data:protected] => Array
    (
        [user] => Array
            (
                [id] => 23
                [username] => gardni
                [email] => email@email.com

我如何将它映射到架构对象?或者更重要的是我自己的应用程序对象?显然这里的解决方案不起作用:

class User implements ResponseClassInterface
{
    public static function fromCommand(OperationCommand $command)
    {
        $parser = OperationResponseParser::getInstance();
        $parsedModel = $parser->parse($command);

        return new self($parsedModel);
    }

    public function __construct(Model $parsedModel)
    {
        // Do something with the parsed model object
    }
}
4

1 回答 1

2

不确定是否按预期工作,但为了从架构中获取对象 - 首先我将 json 更改为包含模型目录的responseTypeaclass和 a :responseClass

"uri": "users/{user_id}",
"summary": "Show user details",
"responseType": "class",
"responseClass": "\\Users\\User",

然后在用户模型中,我在fromCommand

public static function fromCommand(\Guzzle\Service\Command\OperationCommand $command)
{
    $result = $command->getResponse()->json();
    $user = new self();
    $user->setId($result['user']['id']);
    $user->setUsername($result['user']['username']);
    $user->setEmail($result['user']['email']);
    return $user;
}
于 2013-10-29T15:14:56.237 回答