What is a practical way to model lookup tables in Domain Driven Design (DDD)?

前端 未结 5 2143
青春惊慌失措
青春惊慌失措 2021-01-30 07:02

I\'m just learning DDD (Eric Evans book is open in front of me) and I\'ve come across a problem that I can\'t find an answer for. What do you do in DDD when you\'re just trying

5条回答
  •  清歌不尽
    2021-01-30 07:14

    Well I read an article by Mathias Verraes some time ago talking about this here. He talks about Separating value objects in the model from concepts that serve the UI.

    Quoting from the article when asked whether to model Countries as entities or value object:

    There’s nothing intrinsically wrong with modelling countries as entities and storing them in the database. But in most cases, that overcomplicating things. Countries don’t change often. When a country’s name changes, it is in fact, for all practical purposes, a new country. If a country one day does not exist anymore, you can’t simply change all addresses, because possibly the country was split into two countries.

    He suggested a different approach to introduce a new concept called AvailableCountry:

    These available countries can be entities in a database, records in a JSON, or even simply a hardcoded list in your code. (That depends on whether the business wants easy access to them through a UI.)

    countryCode = $countryCode;
        }
    
        public function __toString()
        {
            return $this->countryCode;
        }
    }
    
    final class AvailableCountry
    {
        private $country;
        private $name;
    
        public function __construct(Country $country, $name)
        {
            $this->country = $country;
            $this->name = $name;
        }
    
        /** @return Country */
        public function getCountry()
        {
            return $this->country;
        }
    
        public function getName()
        {
            return $this->name;
        }
    
    }
    
    final class AvailableCountryRepository
    {
        /** @return AvailableCountry[] */
        public function findAll()
        {
            return [
                'BE' => new AvailableCountry(new Country('BE'), 'Belgium'),
                'FR' => new AvailableCountry(new Country('FR'), 'France'),
                //...
            ];
        }
    
        /** @return AvailableCountry */
        public function findByCountry(Country $country)
        {
            return $this->findAll()[(string) $country];
        }
    }
    

    So it seems there is a 3rd solution which is to model look up tables as both value objects and entities.

    BTW make sure u check the comments section for some serious discussions about the article.

提交回复
热议问题