如何在Zend框架2的宁静实现中获取更新中的$ data($ id,$ data)

时间:2015-03-19 06:17:14

标签: php rest zend-framework2

如何在Zend框架2的宁静实现中获取更新中的$ data($ id,$ data)

在邮差中,我正在尝试发送..

{   
    "gender":"1",
    "country":"1",
    "state":"2",
    "city":"23",
    "address1":"27,djkfhasdkjh,kjsdfhdkjs,kjsdh",
    "address2":"ksjadh f,sdkjfhjk",
    "postal_code":"627811",
    "birthdate":"11-12-2045",
    "phone":"0442805565",
    "mobile":"9865521557",
    "blood_group":"o-",
    "weight":"60",
    "height":"5.2",
    "bmi":"10",
}

我的休息代码是:

// update :: update 公共功能更新($ id,$ data){

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");

$data = json_decode($data);
print_r($data); 


if(empty($data)){
        $resp = array('status' => 'failure', 'errorCode' => 516, 'errorMessage' => 'json code format error');
        return new JsonModel($resp);
    }

    if ((strlen($data->mobile) >= 10) && (is_numeric($data->mobile))) {

    }
    else{
        $resp = array('status' => 'failure', 'errorCode' => 517, 'errorMessage' => 'mobile validation error');
        return new JsonModel($resp);
    }

    if(($data->gender == '1') || ($data->gender == '2')){

    }
    else{
        $resp = array('status' => 'failure', 'errorCode' => 517, 'eerorMessage' => 'gender validation error');
        return new JsonModel($resp);
    }


$id  = $this->params('id');


    $sm = $this->getServiceLocator();
    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
    $usersService = new UsersService($dbAdapter);
    $resp = $usersService->update($data,$id);
    $resp = array('status' => 'success');
    return new JsonModel($resp);    
exit;

谢谢,

2 个答案:

答案 0 :(得分:2)

在您的情况下(PUT请求映射到update方法),AbstractRestfulController将从processBodyContent方法获取数据on line 419

此方法将使用requestHasContentType方法检查正确的内容类型(application/json)。因此,如果您将请求中的Content-Type标头设置为application/json,则应自动填充控制器中的$data变量。

所以在你的邮递员中确保你设置了Content-Type标题:

enter image description here

  

注意:您必须自己解码 json数据,这是在控制器中处理的。

答案 1 :(得分:-1)

class MyController extends AbstractRestfulController
{
    public function update($id, $data)
    {
        var_dump($id, $data);
    }
}

将JSON发送到url ... / mycontroller / 1

{"数据":" 15"}

方法PUT

Content-Type:application / json

output:
array(1, 'data' => 15);