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

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

问题描述

我已经在Doctrine 2中实现了价值对象作为自定义DBAL类型,并且一直工作正常。不过我一直在想,这是否是最好的方法。我曾考虑过使用Post Load监听器来实例化Value Objects。还要通过实体访问器实例化它们,后者的优点是我不会实例化比我需要的更多的对象。



我的问题是:哪种方法最好?还是有更好的方法呢?有没有上述的任何问题或不合理的表现点击?

解决方案

嗯,两种方法同样有价值,同时等待价值对象的本机支持


$ b $我个人喜欢第二种方法(在请求时通过访问者实例化),原因有两个:




  • 如前所述,它提供更好的性能,因为转换只有在需要的时候完成;

  • 它将应用程序与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支持。



关于自定义映射类型,我也使用它们,单字段VO( Decimal 多边形,...),但会倾向于将其保留为通用,可重用的类型可以在多个项目中使用,而不是针对特定于项目的单字段VO,我喜欢上述方法。


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:

  • As you mentioned, it offers better performance as the conversion is only done when needed;
  • It decouples your application from Doctrine dependency: you're writing less code that is Doctrine-specific.

An example of this approach:

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
        );
    }
}

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

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天全站免登陆