我有一个基本的服务描述模式,以获得如下所示的用户模型:
{
"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
}
}
答案 0 :(得分:2)
不确定是否有意图但是为了从模式中获取对象 -
首先我更改了json以包含模型目录的responseType
class
和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;
}