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条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败