PHP code example of jeckel-lab / contract

1. Go to this page and download the library: Download jeckel-lab/contract 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/ */

    

jeckel-lab / contract example snippets


/**
 * DiverId is using an `int` as unique identifier
 * @implements Identity<int>
 */
final class DriverId implements Identity
{
}

/**
 * Now Driver can use a DriverId as an identifier
 * @implements Entity<DriverId>
 */
class Driver implements Entity
{
    public function __construct(private DriverId $id)
    {
    }
    
    /**
     * @return DriverId
     */
    public function getId(): Identity
    {
        return $id;
    }
}

    /**
     * @param Event ...$events
     * @return static
     */
    public function addDomainEvent(Event ...$events): static;

    /**
     * @return list<Event>
     */
    public function popEvents(): array;


class MyEntity implement DomainEventAwareInterface
{
    use DomainEventAwareTrait;
    
    /**
     * Example of a use case that add an event to the queue
     * @return self
     */
    public function activateEntity(): self
    {
        $this->activated = true;
        $this->addDomainEvent(new EntityActivated($this->id));
        return $this;
    }
    
    //...
}

new CommandResponse(events: $entity->popEvents());

final class Speed implements ValueObject, ValueObjectFactory
{
    private static $instances = [];

    private function __constructor(private float $speed)
    {
    }
    
    /**
     * @param mixed $value
     * @return static
     * @throws InvalidArgumentException
     */
    public static function from(mixed $speedValue): static
    {
        if (! self::$instances[$speedValue]) {
            if ($speedValue < 0) {
                throw new InvalidArgumentException('Speed needs to be positive');
            }
            self::$instances[$speedValue] = new self($speedValue);
        }
        self::$instances[$speedValue]
    }
    
    // implements other methods
}

// And now
$speed1 = Speed::from(85.2);
$speed2 = Speed::from(85.2);
$speed1 === $speed2; // is true