Doctrine 2 Value Objects

后端 未结 1 1891
情话喂你
情话喂你 2021-02-04 15:45

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 u

1条回答
  •  孤城傲影
    2021-02-04 16:05

    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.

    0 讨论(0)
提交回复
热议问题