简体   繁体   English

Symfony2服务响应

[英]Symfony2 Service Response

i was trying to setup a general service which handles common function i use very often everywhere in my project. 我试图设置一个常规服务来处理我在项目中经常使用的通用功能。 For example if a user wants to purchase something for virtual currency there would be a function which checks, if the user has enough virtual currency in his account. 例如,如果用户想要购买某种虚拟货币,则将有一个功能检查用户帐户中是否有足够的虚拟货币。

If the user doesnt have enough virtual currency I want this function to make a JSOn Response, but of cource, only controllers are allowed to response. 如果用户没有足够的虚拟货币,我希望此函数发出JSOn响应,但是,当然,仅允许控制器响应。 But this means i have to check in every action I use this function, whether the purchase is valid or not. 但这意味着我必须检查使用此功能的每项操作,无论购买是否有效。

Here is the function call in my Controller: 这是我的控制器中的函数调用:

$purchaes= $this->get('global_functions')->payVirtualCurrency($user_id,  $currency_amount);
if($change instanceof JsonResponse){
    return $change;
}

And the function: 和功能:

public function payVirtualCurrency($user_id, $currency_amount){
    $user = $this->dm->getRepository('LoginBundle:User')->findOneById($user_id);
    if($user->getVirtualCurrency() < $currency_amount){
        return new JsonResponse(array('error' => $this->trans->trans('Insufficient amount of virtual Currency')));
    }
    return true;
}

Is there a better way to do this? 有一个更好的方法吗? I really want to avoid doing the same thing in the controller over and over again. 我真的想避免一遍又一遍地在控制器中做同样的事情。

Thanks in advance! 提前致谢!

Two options come to my mind, both are quite elegant solutions but both require little work: 我想到了两个选择,这两个都是不错的解决方案,但都不需要太多工作:

1. Create custom exception listener 1.创建自定义异常侦听器

Create custom exception, let's call it InsufficientMoneyException . 创建自定义异常,我们称其为InsufficientMoneyException Then, your sevice can be as it is, but instead of returning response it throws your custom exception (in case user does not have enough money). 然后,您的服务可以保持原样,但是它不会返回响应,而是引发您的自定义异常(以防用户没有足够的钱)。 Then, you create custom exception listener which listenes to InsufficientMoneyException custom exception and returns your desired JsonResponse . 然后, 创建自定义异常侦听器 ,该侦听器侦听 InsufficientMoneyException自定义异常并返回所需的JsonResponse

2. Create custom annotation 2.创建自定义注释

You can create custom annotation and flag a controller action with this annotation. 您可以创建自定义注释,并使用此注释标记控制器动作。 It would look something like this 看起来像这样

/**
* @MinimumMoneyRequired("50")
*/
public function buyAction()
{
(...)
}

This option is really nice and decoupled but it require quite a lot of configuration. 这个选项确实很不错,而且已经解耦了,但是它需要大量的配置。 This is nice blog post with detailed description how to create custom annotations 这是一篇不错的博客文章,其中详细描述了如何创建自定义注释

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

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