Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Unbreakable Domain Models - PHPUK 2014 London

Unbreakable Domain Models - PHPUK 2014 London

Data Mappers (like Doctrine2) help us a lot to persist data. Yet many projects are still struggling with tough questions:

-Where to put business logic?
-How to protect our code from abuse?
Where to put queries, and how test them?

Let’s look beyond the old Gang of Four design patterns, and take some clues from tactical Domain Driven Design. At the heart of our models, we can use Value Objects and Entities, with tightly defined consistency boundaries. Repositories abstract away the persistence. Encapsulated Operations helps us to protect invariants. And if we need to manage a lot of complexity, the Specification pattern helps us express business rules in the language of the business. These patterns help us evolve from structural data models, to rich behavioral models. They capture not just state and relationships, but true meaning. The presentation is a fast paced introduction to some patterns and ideas that will make your Domain Model expressive, unbreakable, and beautiful.

Mathias Verraes

February 21, 2014
Tweet

More Decks by Mathias Verraes

Other Decks in Technology

Transcript

  1. The domain expert says “A customer must always have an

     email address.” * Could be different for your domain ** All examples are simplified
  2. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_an_email()! {! ! $customer = new Customer();! ! assertThat(! $customer->getEmail(),! equalTo('[email protected]') ! );! ! }! } Test fails
  3. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_an_email()! {! ! $customer = new Customer();! $customer->setEmail('[email protected]');! assertThat(! $customer->getEmail(),! equalTo('[email protected]') ! );! }! } Test passes
  4. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_an_email()! {! ! $customer = new Customer();! assertThat(! $customer->getEmail(),! equalTo(‘[email protected]') ! );! $customer->setEmail(‘[email protected]’);! ! }! } Test fails
  5. final class Customer! {! private $email;! ! public function __construct($email)!

    {! $this->email = $email;! }! ! public function getEmail()! {! return $this->email;! }! }
  6. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_an_email()! {! ! $customer = new Customer(‘[email protected]’);! ! assertThat(! $customer->getEmail(),! equalTo(‘[email protected]') ! );! }! } Test passes
  7. final class ProspectiveCustomer ! {! public function __construct()! {! //

    no email! }! }! ! final class PayingCustomer ! { ! public function __construct($email)! {! $this->email = $email;! }! }
  8. final class ProspectiveCustomer ! {! /** @return PayingCustomer */! public

    function convertToPayingCustomer($email)! { ! //...! }! }! ! final class PayingCustomer ! { ! //...! }
  9. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_a_valid_email()! {! ! $this->setExpectedException(! '\InvalidArgumentException'! );! ! new Customer('malformed@email');! ! }! } Test fails
  10. final class Customer ! {! public function __construct($email)! {! if(

    /* boring validation stuff */) {! throw new \InvalidArgumentException();! }! $this->email = $email;! }! } Test passes
  11. final class Email! {! private $email;! ! public function __construct($email)!

    {! if( /* boring validation stuff */) {! throw new \InvalidArgumentException();! }! $this->email = $email;! }! ! public function __toString() ! {! return $this->email;! } ! } Test passes
  12. final class Customer! {! /** @var Email */! private $email;!

    ! public function __construct(Email $email)! {! $this->email = $email;! }! } Test passes
  13. class CustomerTest extends PHPUnit_Framework_TestCase! {! /** @test */! public function

    should_always_have_a_valid_email()! {! ! $this->setExpectedException(! ‘\InvalidArgumentException’! );! ! new Customer(new Email(‘malformed@email’));! ! }! } Test passes
  14. $order = new Order;! $order->setCustomer($customer);! $order->setProducts($products);! $order->setStatus(Order::UNPAID);! ! ! //

    ...! ! ! $order->setPaidAmount(500);! $order->setPaidCurrency(‘EUR’);! ! $order->setStatus(Order::PAID);! !
  15. $order = new Order;! $order->setCustomer($customer);! $order->setProducts($products);! $order->setStatus(! new PaymentStatus(PaymentStatus::UNPAID)! );!

    ! ! ! $order->setPaidAmount(500);! $order->setPaidCurrency(‘EUR’);! ! $order->setStatus(! new PaymentStatus(PaymentStatus::PAID)! );
  16. $order = new Order;! $order->setCustomer($customer);! $order->setProducts($products);! $order->setStatus(! new PaymentStatus(PaymentStatus::UNPAID)! );!

    ! ! ! $order->setPaidMonetary(! new Money(500, new Currency(‘EUR’))! );! $order->setStatus(! new PaymentStatus(PaymentStatus::PAID)! );
  17. $order = new Order($customer, $products);! // set PaymentStatus in Order::__construct()!

    ! ! ! ! ! ! ! $order->setPaidMonetary(! new Money(500, new Currency(‘EUR’))! );! $order->setStatus(! new PaymentStatus(PaymentStatus::PAID)! );
  18. $order = new Order($customer, $products);! ! ! ! ! !

    ! ! ! $order->pay(! new Money(500, new Currency(‘EUR’))! );! // set PaymentStatus in Order#pay()! !
  19. $order = $customer->order($products);! ! ! ! ! ! ! !

    ! $customer->payFor(! $order,! new Money(500, new Currency(‘EUR’))! );! !
  20. class CustomerIsPremium implements CustomerSpecification ! {! private $orderRepository;! public function

    __construct(! OrderRepository $orderRepository! ) {...}! ! /** @return bool */! public function isSatisfiedBy(Customer $customer) ! {! $count = $this->orderRepository->countFor($customer);! return $count >= 3;! }! }! ! $customerIsPremium = new CustomerIsPremium($orderRepository)! if($customerIsPremium->isSatisfiedBy($customer)) {! // send special offer! }!
  21. $customerIsPremium = new CustomerIsPremium;! ! $aCustomerWith2Orders = ...! $aCustomerWith3Orders =

    ...! ! assertFalse(! $customerIsPremium->isSatisfiedBy($aCustomerWith2Orders)! );! ! assertTrue(! $customerIsPremium->isSatisfiedBy($aCustomerWith3Orders)! );! ! !
  22. interface CustomerIsPremium ! extends CustomerSpecification! ! final class CustomerWith3OrdersIsPremium !

    implements CustomerIsPremium! ! final class CustomerWith500EuroTotalIsPremium! implements CustomerIsPremium! ! final class CustomerWhoBoughtLuxuryProductsIsPremium! implements CustomerIsPremium! ! ...!
  23. final class SpecialOfferSender! {! private $customerIsPremium;! ! ! public function

    __construct(! CustomerIsPremium $customerIsPremium) {...}! ! ! public function sendOffersTo(Customer $customer) ! {! if($this->customerIsPremium->isSatisfiedBy(! $customer! )) ! {! // send offers...! }! }! }!
  24. ! <!-- if you load services_amazon.xml: -->! <service id="customer.is.premium"! class="CustomerWith500EuroTotalIsPremium">

    ! ! <!-- if you load services_ebay.xml: -->! <service id="customer.is.premium"! class="CustomerWith3OrdersIsPremium"> ! ! ! <!-- elsewhere -->! <service ! id=”special.offer.sender”! class=”SpecialOfferSender”>! <argument type=”service” id=”customer.is.premium”/>! </service>
  25. interface CustomerRepository! {! public function add(Customer $customer);! ! public function

    remove(Customer $customer);! ! /** @return Customer */! public function find(CustomerId $customerId);! ! /** @return Customer[] */! public function findAll();! ! /** @return Customer[] */! public function findRegisteredIn(Year $year);! }!
  26. interface CustomerRepository! {! ! /** @return Customer[] */! public function

    findSatisfying(! CustomerSpecification $customerSpecification! );! ! }! ! ! // generalized:! $objects = $repository->findSatisfying($specification);!
  27. class DbCustomerRepository implements CustomerRepository! {! /** @return Customer[] */! public

    function findSatisfying(! CustomerSpecification $specification) ! {! ! return array_filter(! $this->findAll(),! function(Customer $customer) use($specification) {! return $specification->isSatisfiedBy($customer);! } ! );! ! }! }!
  28. final class CustomerWith3OrdersIsPremium! implements CustomerSpecification! {! public function asSql() {!

    return ‘SELECT * FROM Customer...’;! }! }! ! ! // class DbCustomerRepository ! public function findSatisfying($specification) ! {! return $this->db->query($specification->asSql()); ! }
  29. $expectedCustomers = array_filter(! $repository->findAll(),! // filter…! );! ! $actualCustomers =

    ! $repository->findSatisfying($specification);! ! assertThat($expectedCustomers, equalTo($actualCustomers));