简体   繁体   English

Symfony2:将发布请求从一个控制器发送到另一个

[英]Symfony2: send post request from one controller to another

I am developing an API method to save a user to the database by a given json. 我正在开发一种API方法,以通过给定的json将用户保存到数据库。

The method looks something like this: 该方法如下所示:

/**
 * Create user.
 *
 * @Rest\View
 */
public function cpostAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if(!empty($content)){
        $params = json_decode($content, true);
    }

    $user = new User();
    $user->setUsername($params['username']);
    $user->setFbUserid($params['id']);

    $em = $this->getDoctrine()->getManager();
    $em->persist($user);
    $em->flush();

    return new Response(
      $this->get('serializer')->serialize($user, 'json'),
      201,
      array('content-type' => 'application/json')
    );
}

I want to call it in several ways: Once via ajax, and once in a different controller. 我想用几种方式来称呼它:一次是通过ajax,一次是在其他控制器中。 My ajax request looks like this: 我的ajax请求看起来像这样:

  $.ajax({
    type: "POST",
    url: "/api/users",
    data: '{"id":"11111","username":"someone"}'
  })
  .done(function(data){
  })
  .fail(function(data){
  });

And now, to come to my question: I want to do the same inside a controller! 现在,我要问一个问题:我想在控制器内做同样的事情! For example: 例如:

public function checkFBUserAction()
{
    $user_data = '{"id":"2222","username":"fritz"}'
    // post data to /api/users (router: _api_post_users) via POST
    // get response json back

}

How can i achieve this?? 我怎样才能做到这一点?

In your second action you can forward the request: 在第二步中,您可以转发请求:

public function checkFBUserAction()
{
   $user_data = array("id"=>"2222","username"=>"fritz");
   $this->getRequest->headers->set('Content-Type'), 'application/json');
   $this->getRequest()->request->replace(array(json_encode($user_data)));
   $this->forward('YourBundle:ControllerName:cpost');
}

如果您想将此功能用作服务,更好的方法是将其移动到Symfony服务中,并在控制器中以及您想在项目中的任何位置调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM