https://github.com/krakphp/adt
ADT (Algebraic Data Types) in PHP
https://github.com/krakphp/adt
adt algebraic-data-types enum enumeration php php7
Last synced: 10 months ago
JSON representation
ADT (Algebraic Data Types) in PHP
- Host: GitHub
- URL: https://github.com/krakphp/adt
- Owner: krakphp
- Created: 2019-07-10T05:58:55.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2019-09-15T04:37:57.000Z (almost 7 years ago)
- Last Synced: 2025-08-16T15:49:08.363Z (10 months ago)
- Topics: adt, algebraic-data-types, enum, enumeration, php, php7
- Language: PHP
- Size: 8.79 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# ADT (Algebraic Data Types)
Poor man's implementation of [Algebraic Data Types](https://en.wikipedia.org/wiki/Algebraic_data_type) in PHP.
Also known as an enum with an associated value in other languages like Swift or Rust.
## Installation
Install with composer at `krak/adt`
## Usage
```php
numberSystem = $numberSystem;
$this->manufacturer = $manufacturer;
$this->product = $product;
$this->check = $check;
}
}
final class QrCode extends Barcode {
public $productCode;
public function __construct(string $productCode) {
$this->productCode = $productCode;
}
}
$barcode = new QrCode('abc123');
// requires that all cases are set or exception is thrown
$oneOrTwo = $barcode->match([
Upc::class => function(Upc $upc) { return 1;},
QrCode::class => function(QrCode $qrCode) { return 2; },
]);
// allow a default value
$oneOrNull = $barcode->matchWithDefault([
Upc::class => function(Upc $upc) { return 1; }
]);
// return static values
$threeOrFour = $barcode->match([
Upc::class => 3,
QrCode::class => 4,
]);
// static constructors
$qrCode = Barcode::qrCode('abc123');
```
### Autoloading Concerns
With the example above, if you try to create a QrCode or Upc before ever referencing the Barcode class, you'll likely get a file not found when using composer's psr-4 autoloader.
You can get around this a few ways:
1. Utilize class mapping
2. Include the enum class file in the composer autoload.files section (something like [php-inc](https://github.com/krakphp/php-inc) could make that easier)
3. Utilize static constructors provided by the base ADT class:
```php