PHP code example of withinboredom / records

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

    

withinboredom / records example snippets


use Withinboredom\Record;
use Withinboredom\Record\Attributes\ConstrainWith;

readonly class User extends Record {
	public string $name;
	public string $email;
	
	#[ConstrainWith(changeTogether: 'email')]
	#[ConstrainWith(changeTogether: 'name')]
	public int $id;
    
	public static function from(string $name, int $id, string $email): static {
		return self::fromArgs(name: $name, id: $id, email: $email);
	}
}

$user1 = User::from('Rob', 12, '[email protected]');
// later
$user2 = User::from('Rob', 12, '[email protected]');

assert($user1 === $user2); // true

$bob = $user1->with(name: 'Bob');

assert($user1 !== $bob); // true

$other = $bob->with(id: 42); // throws a LogicException

class Currency extends Record {
  public int $pennies;
  
  #[Immutable]
  public string $code;
  
  public function from(string $code, int $pennies): self {
    return self::fromArgs(code: $code, pennies: $pennies);
  }
}

class Currency extends Record {
  public int $pennies;
  
  #[ConstrainWith('pennies')]
  public string $code;
  
  public function from(string $code, int $pennies): self {
    return self::fromArgs(code: $code, pennies: $pennies);
  }
}

$balance = Currency::from('USD', 42);
$transfer = $balance->with(code: 'EUR', pennies: 42); // constrain just