在Symfony2与Doctrine2,对象=实体? [英] On Symfony2 with Doctrine2, does Object = Entity?

查看:107
本文介绍了在Symfony2与Doctrine2,对象=实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个用户类:

  $ user =新用户(1); 
$ user-> setName('Bob'); //将bob保存到ID为1的数据库
$ user-> setGender('Male'); //将男保存到ID为1的数据库

echo $ user-> getName(); //显示bob
echo $ user-> getGender(); //显示男

echo $ user-> getDesignation()//显示Bob先生

现在,在Symfony2中,使用Doctrine2,似乎 Entity 是用于与数据库建立链接的对象。所以我认为所有的 setName() setGender() getName() code>&函数应该在一个Bundle的 Entity 目录中的文件中(因为这些函数是UPDATE或



但是,如果 getDesignation()

  public function getDesignation(){
if($ this-> getGender()=='Male')返回Mr.$ - >的getName();
else returnMs.$ this-> getName();
}

可以放置一个绝对没有数据库链接的函数实体?这是不是一个不好的做法?

解决方案


放置一个绝对没有链接数据库?


是的,没关系。但是仔细看看,它仍然有一些链接到数据库,因为它使用了最初来自持久层(数据库)的性别和名称数据。


这不是一个不好的做法吗?


这不是一个糟糕的做法,其实这是非常有用的。它可以帮助您在将代码从数据库访问中解耦出来时,使用模型对象中的持久层。


Let's say I have a User class :

$user = new User(1);
$user->setName('Bob'); // save "bob" to database with ID 1
$user->setGender('Male'); // save "male" to database with ID 1

echo $user->getName(); // display bob
echo $user->getGender(); // display "male";

echo $user->getDesignation() // display "Mr. Bob"

Now, in Symfony2, with Doctrine2, it seems that Entity is an object which is used to made link with the database. So I think all the setName(), setGender(), getName() & getGender() functions should go inside a file which is in the Entity directory of a Bundle (because those functions UPDATE or SELECT data from the database).

But what about getDesignation() ?

public function getDesignation() {
  if ($this->getGender() == 'Male') return "Mr. ".$this->getName();
  else return "Ms. ".$this->getName();
}

Is it OK to put a function which has absolutely no link with the database in an Entity ? Is it not a bad practice ?

解决方案

Is it OK to put a function which has absolutely no link with the database?

Yes that's okay. But look closely, it is still somewhat "linked" to the database as it makes use of the gender and name data which originally comes from the persistence layer (database).

Is it not a bad practice?

That's not at all bad practice, in fact it's something very useful. It helps you to make use of the persistence layer in your model objects while decoupling your code from the database access.

这篇关于在Symfony2与Doctrine2,对象=实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆