dpafea04148 2014-01-23 18:01
浏览 36

如何在Symfony2中包装控制器的操作?

Is it possible to wrap some controller's actions in a custom logic in Symfony2?

I would like to create an "AJAX" controller in order to handle all AJAX requests in my application. I want to remove boilerplate code from my actions to make application logic lighter. Here's some points i want to implement through wrapper:

  1. Wrap action call in a try ... catch block in order to catch all possible exceptions and transform output to a JSON one instead of general 500 HTML error pages. So I can gracefully handle them on a client side.
  2. Return plain arrays from the action calls to rewrite them later and transform them into a proper JsonResponse objects.

If it's possible to implement such a wrapper, is it also possible to enable it on a route basis?

UPDATE:

Here's my example:

/**
 * It is now.
 * @return JsonResponse
 */
public function someAction()
{
    try {

        // Some business logic here.
        $foo = getFoo();
        $bar = getBar($foo);

        // Sending response.
        return new JsonResponse([
            'success' => true,
            'data'    => [
                'foo' => $foo,
                'bar' => $bar,
            ],
        ]);

    } catch (\Exception $exception) {

        // Handle exception here. Translate error message, etc.

        return new JsonResponse([
            'success' => false,
            'message' => $exception->getMessage(),
            'code'    => $exception->getCode(),
        ]);
    }
}

/**
 * How I want it to be.
 * @return array
 */
public function someBetterAction()
{
    // Some business logic here.
    $foo = getFoo();
    $bar = getBar($foo);

    // Sending response.
    return [
        'foo' => $foo,
        'bar' => $bar,
    ];
}

In other words I just want to move exception handling and output formatting to a wrapping layer in order to make action lighter.

  • 写回答

1条回答 默认 最新

  • dousuo8400 2014-01-25 00:47
    关注

    You could use a custom exception handler like FOSRestBundle (& Docs) which would (obviously) handle any exceptions that were created through the course of your actions.

    评论

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'