Simple CQRS - reduce coupling, allow the model(s) to evolve Best Php training trivandrum

Simple CQRS - reduce coupling, allow the model(s) to evolve


CQRS - not a complicated thing

All the legacy projects I've encountered so far use this style of storing and retrieving state. It comes with a certain programming style that is not quite beneficial for the maintainability of the application. When writing a new feature for such an application you will start with getting all the ingredients in place. You need some information, and you need some dependencies. If you're unlucky, you still fetch your dependencies from some global static place like good old Zend_Registry or sfContext. Equally bad, you'll fetch your information from the central database. This database contains tables with dozens of columns. It's the single source of truth. "Where is this piece of information? Ah, in table XYZ". So now you use the ORM to fetch a record and automatically turn it into a useful entity for you.

Reduce the level of coupling

A recipe for read models

  1. Whenever you feel the need to fetch some information, or get an answer to a specific question, and you're tempted to go to the repository and load one or more entities (and related entities), stop and think:
  2. final class ProductTheCustomerOrdered
    {
        private $productId;
        private $productName;
        private $dateOfOrder;
    
        public function __construct(int $productId, string $productName, string $dateOfOrder)
        {
            ...
        }
    }
    
  3. interface OrderHistory
    {
        /**
         * @return ProductTheCustomerOrdered[]
         */
        public function productsTheCustomerOrdered(CustomerId $customerId);
    }
    
  4. final class SomeService
    {
        private $orderHistory;
    
        public function __construct(OrderHistory $orderHistory)
        {
            $this->orderHistory = $orderHistory;
        }
    
        public function someMethod(CustomerId $customerId)
        {
            $products = $this->orderHistory->productsTheCustomerOrdered($customerId);
    
            // do something with $products
        }
    }
    
  5. final class OrderHistorySql implements OrderHistory
    {
        public function productsTheCustomerOrdered(CustomerId $customerId)
        {
            // perform some smart query, fetching only what you need
            $records = ...;
    
            return array_map(function($record) {
                return new ProductTheCustomerOrdered(...);
            }, $records);
        }
    }
    

Dealing with inconsistent data

Conclusion

Comments

Popular posts from this blog

A Tailwind CSS Preset for Laravel 5.5

Short and safe array iteration

PHPStorm's performance