PHP code example of sammakescode / actions

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

    

sammakescode / actions example snippets




namespace App;

use \SamMakesCode\Actions\BusinessRules\BusinessRulesInterface;

class OrderMustNotBeDispatched implements BusinessRulesInterface
{
    public function __construct(
        private readonly Order $order,    
    ) {}
    
    public function isSatisfied(): bool
    {
        return !in_array(
            $this->order->status,
            [
                'dispatched',
                'delivered',
                'complete',
            ]
        );
    }
    
    public function getFailureMessage(): string
    {
        return 'Cannot perform action because the order has been dispatched!';
    }
}



namespace App;

use \SamMakesCode\Actions\Actions\BaseAction;

class CancelOrder extends BaseAction
{
    public function __construct(
        private readonly Order $order,
    ) {
        $this->registerBusinessRules([
            new OrderMustNotBeDispatched($this->order),
        ]);
    }
    
    public function handle()
    {
        $this->order->cancel();
    }
}



$order = new \App\Order;
$order->status = 'dispatched';

$action = new \App\CancelOrder($order);

// Throws \SamMakesCode\Actions\Exceptions\BusinessRulesNotSatisfied because dispatched orders can't be cancelled
$action->perform();

CancelOrder::do($order);