Php 在REST API中使用Symfony2表单时操作POST数据
背景: 我正在symfony上编写一个restfulapi。我希望客户端能够使用内容类型application/json发布到url,并发布控制器操作正在寻找的json对象 我使用一个非常基本的控制器设置。为了演示的目的,让我们假设我正在尝试验证一个简单的用户名密码组合Php 在REST API中使用Symfony2表单时操作POST数据,php,symfony,Php,Symfony,背景: 我正在symfony上编写一个restfulapi。我希望客户端能够使用内容类型application/json发布到url,并发布控制器操作正在寻找的json对象 我使用一个非常基本的控制器设置。为了演示的目的,让我们假设我正在尝试验证一个简单的用户名密码组合 public function loginAction( Request $request ) { $user = new ApiUser(); $form = $this->createForm(new
public function loginAction( Request $request )
{
$user = new ApiUser();
$form = $this->createForm(new ApiUserType(), $user);
if ( "POST" == $request->getMethod() ) {
$form->bindRequest($request);
if ( $form->isValid() ) {
$em = $this->getDoctrine()->getEntityManager();
$repo = $this->getDoctrine()->getRepository('ApiBundle:ApiUser');
$userData = $repo->findOneByUsername($user->getUsername());
if ( is_object($userData) ) {
/** do stuff for authenticating **/
}
else{
return new Response(json_encode(array('error'=>'no user by that username found')));
}
else{
return new Response(json_encode(array('error'=>'invalid form')));
}
}
}
现在我遇到的问题是,在奶牛回家之前,我曾经尝试过var_转储它,因为无论出于什么原因,symfony都不想获取应用程序/json内容体并使用该数据填充表单数据
表格名称:api_apiuser
字段:用户名、密码
处理这类任务的最佳方式是什么。我愿意接受建议,只要我能让这个工作。感谢您花时间处理此事。您需要访问原始请求正文,然后使用json_解码。您可能需要将
bindRequest
方法更改为以下内容:
public function bindRequest(Request $request)
{
if($request->getFormat() == 'json') {
$data = json_decode($request->getContent());
return $this->bind($data);
} else {
// your standard logic for pulling data form a Request object
return parent::bind($request);
}
}
我还没有真正弄乱SF2,所以这更多的是基于API、sf1.x的经验以及我从框架演示中获得的东西的猜测。最好是创建一个完全不同的方法,如
bindJsonRequest
,这样事情会更整洁一些。是的,表单在绑定过程中等待的是一个数组,其中包含与ApiUser属性相对应的键
因此,如果您发送带有字符串的POST请求:
{ username: 'user', password: 'pass' }
您必须使用json\u decode
将其转换为数组,例如:
$data = json_decode($request->getContent()); // $request->request->get('json_param_name');
然后使用$form->bind($data)将该数组绑定到表单代码>
该表单将更新与数组键(用户名、密码)对应的ApiUser属性
如果您正在构建一个RESTful json api,我建议您使用序列化器/转换器自动化此过程,例如,在检查方法是否为post之后,在将请求绑定到表单之前,我实际上找到了一种类似的方法来解决此问题。我这样做:
if ( "POST" === $request->getMethod() ) {
if (0 === strpos($request->headers->get('Content-Type'), 'application/json')){
$data = json_decode($request->getContent(), true);
$request->request->replace(is_array($data) ? $data : array());
}
$form->bindRequest($request);
/** Rest of logic **/
}