教义 2 价值对象 [英] Doctrine 2 Value Objects

查看:14
本文介绍了教义 2 价值对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在 Doctrine 2 中将值对象实现为自定义 DBAL 类型,并且运行良好.但是我一直想知道这是否是最好的方法.我考虑过使用 Post Load 侦听器来实例化值对象.在请求时也通过实体访问器实例化它们,后者的优点是我不会实例化比我需要的更多的对象.

I have been implementing value objects as custom DBAL types in Doctrine 2 and it's been working OK. However I have been wondering if this is the best way. I've thought about using the Post Load listener to instantiate the Value Objects. Also instantiating them through Entity accessors when requested, the advantage with the latter would be that I would not instantiate more objects than I need.

我的问题是:哪种方法最好?或者有更好的方法吗?以上是否存在任何问题或不合理的性能问题?

My question is: which method is best? Or is there a better way to do it? Are there any gotchas or unreasonable performance hits with the above?

推荐答案

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

IMHO, both approaches are equally valuable, while waiting for native support for value objects.

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

I personally favor the second approach (instantiating them through accessors when requested) for two reasons:

  • 正如您所提到的,它提供了更好的性能,因为只有在需要时才进行转换;
  • 它将您的应用程序与 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
        );
    }
}

当 Doctrine 提供原生 VO 支持时,此代码将相当容易重构.

This code will be fairly easy to refactor when Doctrine will offer native VO support.

关于自定义映射类型,我也使用它们,用于单字段 VO(DecimalPointPolygon、...) 但倾向于将它们保留用于可在多个项目中使用的通用、可重用类型,而不是用于我偏爱上述方法的项目特定的单字段 VO.

About custom mapping types, I do use them as well, for single-field VO (Decimal, Point, Polygon, ...) but would tend to reserve them for general-purpose, reusable types that can be used across multiple projects, not for project-specific single-field VO where I would favor the approach above.

这篇关于教义 2 价值对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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