在Symfony控制器中使用JSON

时间:2017-07-18 10:23:27

标签: json symfony

我正在寻找一种从我的Symfony(2.6 btw)控制器执行一点JSON的方法,而不是其他操作(将数据发布到数据库中)

实际上,有一个带有控制器的注册页面,它将数据放入数据库,然后将用户重定向到另一个页面。但我需要我的控制器执行一点JSON来使用Mailchimp API。

我发现了很多关于如何呈现JSON响应的文档,但是,在我看来,它并不是我想要的。

有我的控制器

public function registerAction(Request $request)
{
    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    $userManager = $this->get('fos_user.user_manager');
    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->createUser();
    $user->setEnabled(true);

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    $form = $formFactory->createForm();
    $form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {

        // Gestion du type d'utilisateur et ajout du role
        $user_type = $form->get('user_profile')->get('type')->getData();
        $new_role = $this->roles[$user_type];          

        $event = new FormEvent($form, $request);
        $user = $event->getForm()->getData();
        $user->addRole($new_role);

        $user->getUserProfile()->setEmail($user->getEmail());

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    return $this->render('FOSUserBundle:Registration:register.html.twig', array(
        'form' => $form->createView(),
    ));
}

有我的JSON请求

{
"email_address": "$email",
"status": "subscribed",
"merge_fields": {
    "FNAME": "$name",
    "LNAME": "$lastname",
    "DATE": "$date"

} }

那么,如何使用此控制器执行此JSON?

提前感谢您的帮助(对不起我的优秀英语)

2 个答案:

答案 0 :(得分:1)

您可能希望从数组创建JSON而不是尝试传递变量。尝试:

$data = [
    'email_address' => $email,
    'status' => 'subscribed',
    'merge_fields' => [
        'FNAME' => $name,
        'LNAME' => $lastname,
        'DATE' => $date,
    ],
];
$json = json_encode($data);

然后我假设这个数据在POST请求中被发送到MailChimp?如果是这样,您可以使用Guzzle将数据发送到MailChimp:

首先通过运行:

在composer中添加guzzle依赖项
composer require guzzlehttp/guzzle

然后发送数据:

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['body' => $data]);

要发送JSON而不是原始数据,请执行以下操作:

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['json' => $data]);

根据响应状态,您可以随后处理逻辑。

答案 1 :(得分:0)

您也可以使用JsonResponse(Symfony \ Component \ HttpFoundation \ JsonResponse)实现此目的

   use Symfony\Component\HttpFoundation\JsonResponse;
    ...
// if you know the data to send when creating the response
$data = [
    'email_address' => $email,
    'status' => 'subscribed',
    'merge_fields' => [
        'FNAME' => $name,
        'LNAME' => $lastname,
        'DATE' => $date,
    ]
];
$response = new JsonResponse($data);
return $response;

此处有更多详情https://symfony.com/doc/current/components/http_foundation.html