PHP code example of hemp / machinery

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

    

hemp / machinery example snippets


use Hemp\Machinery\MachineryState;
use Hemp\Machinery\MachineryEnumeration;

enum OrderStatus: string implements MachineryState
{
    use MachineryEnumeration;

    case Processing : 'processing';
    case Shipped : 'shipped';
    case Delivered : 'delivered';
    
    public static function transitions(): array
    {
        return [
            self::Processing->value => [
                self::Shipped
            ],
            self::Shipped->value => [
                self::Delivered
            ],
            self::Delivered->value => [
                // This is the final state...
            ]
        ];
    }
}

use Hemp\Machinery\Machinery;

OrderStatus::Processing->canTransitionTo(OrderStatus::Shipped); // true
OrderStatus::Processing->transitionTo(OrderStatus::Shipped); // state is now 'shipped'

OrderStatus::Shipped->canTransitionTo(OrderStatus::Delivered); // true
OrderStatus::Shipped->transitionTo(OrderStatus::Delivered); // state is now 'delivered'

OrderStatus::Delivered->canTransitionTo(OrderStatus::Processing); // 
OrderStatus::Delivered->transitionTo(OrderStatus::Processing); // Throws an exception...

use Hemp\Machinery\Machinery;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use Machinery;

    protected $casts = [
        'status' => OrderStatus::class
    ];
}

$order = Order::create([
    'status' => OrderStatus::Processing
]);

$order->status->is(OrderStatus::Processing); // true
$order->status->canTransitionTo(OrderStatus::Shipped); // true

$order->status->transitionTo('status', OrderStatus::Shipped, function () {
    // Perform any actions that need to be done when the state changes...
});

$order->status->is(OrderStatus::Shipped); // true

$order->status->canTransitionTo('status', OrderStatus::Processing); // false

$order->status->transitionTo('status', OrderStatus::Delivered); // Throws an exception...