PHP code example of cjsaylor / libdomain

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

    

cjsaylor / libdomain example snippets


use Cjsaylor\Domain\ValueObject\ValueObjectInterface;
use Cjsaylor\Domain\Behavior\ReadAccessable;

class ConcreteEntity implements ValueObjectInterface {
  use ReadAccessable;
}


use \Cjsaylor\Domain\Entity;
use \Cjsaylor\Domain\ValueObject;

class Email extends ValueObject
{
  public function __construct(string $value) {
    // Validate an email address here
    $this['value'] = $value;
  }

  public function __toString() {
    return $this['value'];
  }
}

class User extends Entity
{
  public function offsetSet($offset, $value) : void
  {
    if ($offset === 'email' && !$value instanceof Email) {
      throw new \LogicException('Email must be an email value object!');
    }
    parent::offsetSet($offset, $value);
  }
}

$user = new User([
  'email' => new Email('[email protected]')
]);

use \Cjsaylor\Domain\CollectionEntity;

class UserGroup extends CollectionEntity
{
  // Here, we set the expectation that this collection can take only users
  public function __construct(array $data = [], User ...$users) {
    parent::__construct($data, ...$users);
  }

  // Here's a method to add additional users post-construction
  public function add(User $user) {
    $this->getItems()[] = $user;
  }
}

$users = [
  new User([
    'id' => 1,
    'email' => new Email('[email protected]')
  ]),
  new User([
    'id' => 2,
    'email' => new Email('[email protected]')
  ])
];

$userGroup = new UserGroup([
  'id' => 1,
  ...$users
]);

class User extends Entity {

  public function setEmail(Email $email) {
    $this->data['email'] = $email;
  }

}

// Would produce an error as `setEmail` would be called and would not match the type.
$user = new User(['email' => '[email protected]']);

// Valid
$user = new User(['email' => new Email('[email protected]')]);

use Cjsaylor\Domain\Behavior\PropertyLimitable;
use Cjsaylor\Domain\Behavior\PropertyLimitTrait;

class User extends Entity implements PropertyLimitable {
  use PropertyLimitTrait;

  public function concreteAttributes() {
    return ['id', 'email'];
  }

}

$user = new User();
$user['id'] = 1; // OK!
$user['first_name'] = 'Chris'; // Has no affect and is not set.