背景:
我正在symfony上编写一个RESTful API.我希望客户端能够使用内容类型application / json发布到url并发布控制器操作正在查找的表单的json对象.
我正在使用一个非常基本的控制器设置.让我们假设为了演示目的,我试图验证一个简单的用户名密码组合.
- 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_dumping这个直到奶牛回家,这是因为symfony不想拿应用程序/ json内容体并使用该数据来填充表单数据.
表格名称:api_apiuser
字段:用户名,密码
处理此类任务的最佳方法是什么.只要我能做到这一点,我愿意接受建议.感谢您抽出宝贵时间.
您需要访问RAW请求主体,然后使用json_decode.您可能需要将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,exp猜测.与sf1.x和我从框架的演示文稿中获得的东西.制作一个完全不同的方法(如bindJsonRequest)也可能更好,所以事情要整洁一些.