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 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目