douba9776 2016-12-05 09:07
浏览 30
已采纳

将字段添加到控制器中的Symfony实体是否被视为不良做法?

Is it considered a bad practice to add fields to Symfony entity in controller? For example lets say that I have a simple entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;



    public function __construct()
    {
        parent::__construct();
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }
}

And then in UserController.php I want to do the following:

foreach($users as $user){
    $user->postsCount = someMethodThatWillCountPosts();
}

So later that postsCount can be displayed in Twig. Is it a bad practice?

Edit:

It's important to count posts on side of mysql database, there will be more than 50.000 elements to count for each user.

Edit2:

Please take a note that this questions is not about some particular problem but rather about good and bad practices in object oriented programming in Symfony.

  • 写回答

2条回答 默认 最新

  • douzong7283 2016-12-05 11:23
    关注

    "rather about good and bad practices in object oriented programming"

    If that's the case then you really shouldn't have any business logic in controller, you should move this to services.

    So if you need to do something with entities before passing them to twig template you might want to do that in specific service or have a custom repository class that does that (maybe using some other service class) before returning the results.

    i.e. then your controller's action could look more like that:

    public function someAction()
    {
        //using custom repository
        $users = $this->usersRepo->getWithPostCount()
    
        //or using some other service
        //$users = $this->usersFormatter->getWithPostCount(x)
    
        return $this->render('SomeBundle:Default:index.html.twig', [
               users => $users
         ]);
    }
    

    It's really up to you how you're going to do it, the main point to take here is that best practices rather discourage from having any biz logic in controller. Just imagine you'll need to do the same thing in another controller, or yet some other service. If you don't encapsulate it in it's own service then you'll need to write it every single time.

    btw. have a read there: http://symfony.com/doc/current/best_practices/index.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿