PHP code example of bus-factor / ddd

1. Go to this page and download the library: Download bus-factor/ddd library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bus-factor / ddd example snippets


/**
 * @method static Currency EUR()
 * @method static Currency USD()
 */
class Currency extends \BusFactor\Ddd\ValueObject\Enum {
    public const EUR = 'EUR';
    public const USD = 'USD';
}

class Decimal implements \BusFactor\Ddd\ComparableInterface {
    use \BusFactor\Ddd\ComparableTrait;

    // ...
    public function compareTo(\BusFactor\Ddd\ComparableInterface $subject) : int {
    } 
    // ...
}

class Money implements \BusFactor\Ddd\ComparableInterface {
    use \BusFactor\Ddd\ComparableTrait;

    /** @var Decimal $amount*/
    private $amount;
    /** @var Currency $currency */
    private $currency;

    /**
     * @param Decimal $amount
     * @param Currency $currency
     */
    public function __construct(Decimal $amount, Currency $currency) {
        $this->amount = $amount;
        $this->currency = $currency;
    }

    /**
     * @param \BusFactor\Ddd\ComparableInterface $subject
     * @return int
     */
    public function compareTo(\BusFactor\Ddd\ComparableInterface $subject) : int {
        $comparable = $subject instanceof static::class
            && $this->currency === $subject->currency;

        if (!$comparable) {
            throw new LogicException('Incompatible currencies');
        }

        return $this->amount->compareTo($subject->amount);
    }
}

$money = new Money(new Decimal(/* ... */), Currency::EUR());
$otherMoney = new Money(new Decimal(/* ... */), Currency::EUR());