学说2价值对象

Joh*_*ohn 8 doctrine doctrine-orm

我一直在Doctrine 2中将值对象实现为自定义DBAL类型,并且它一直正常工作.但是我一直想知道这是不是最好的方法.我已经考虑过使用Post Load监听器来实例化Value Objects.同时在请求时通过Entity访问器实例化它们,后者的优点是我不会实例化比我需要的更多的对象.

我的问题是:哪种方法最好?或者有更好的方法吗?以上是否有任何陷阱或不合理的表现?

Ben*_*min 8

恕我直言,这两种方法同样有价值,同时等待对价值对象的原生支持.

我个人赞成第二种方法(在请求时通过访问器实例化它们)有两个原因:

  • 正如您所提到的,它提供了更好的性能,因为只在需要时才进行转换;
  • 它将您的应用程序与Doctrine依赖关系分离:您编写的代码是Doctrine特有的.

这种方法的一个例子:

class User
{
    protected $street;
    protected $city;
    protected $country;

    public function setAddress(Address $address)
    {
        $this->street  = $address->getStreet();
        $this->city    = $address->getCity();
        $this->country = $address->getCountry();
    }

    public function getAddress()
    {
        return new Address(
            $this->street,
            $this->city,
            $this->country
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

当Doctrine将提供本机VO支持时,此代码将非常容易重构.

关于自定义映射类型的,我使用它们为好,单场VO( ,,Decimal ,...),但往往会保留他们为通用型,可在多个项目中使用可重复使用的类型,而不是项目-特定的单场VO我赞成上面的方法.PointPolygon