PHP code example of tetthys / domain-kernel

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

    

tetthys / domain-kernel example snippets




declare(strict_types=1);

namespace App\Exceptions;

use Tetthys\DomainKernel\ServiceFailureReason;

/**
 * Failure reasons for ItemService.
 */
enum ItemFailureReason: string implements ServiceFailureReason
{
    case NEGATIVE_PRICE = 'negative_price';

    public function code(): string
    {
        return $this->value;
    }

    public function message(): string
    {
        return match ($this) {
            self::NEGATIVE_PRICE => 'Price cannot be negative.',
        };
    }
}



declare(strict_types=1);

namespace App\Exceptions;

use Tetthys\DomainKernel\ServiceFailureException;

/**
 * Single failure type for ItemService.
 */
final class ItemFailure extends ServiceFailureException
{
}



declare(strict_types=1);

namespace App\Service;

use App\Exceptions\ItemFailure;
use App\Exceptions\ItemFailureReason;
use Tetthys\DomainKernel\ServiceFailable;
use Tetthys\DomainKernel.ServiceFailureException;
use Tetthys\DomainKernel.ServiceFailureReason;

/**
 * Minimal pure PHP service using abortWith().
 */
final class ItemService
{
    use ServiceFailable;

    /**
     * Required by ServiceFailable.
     */
    protected function newServiceFailure(
        ServiceFailureReason $reason,
        array $context = [],
    ): ServiceFailureException {
        /** @var ItemFailureReason $reason */
        return new ItemFailure($reason, $context);
    }

    public function calculatePrice(int $price): int
    {
        if ($price < 0) {
            $this->abortWith(
                ItemFailureReason::NEGATIVE_PRICE,
                ['given_price' => $price],
            );
        }

        return $price * 2; // some logic
    }
}



declare(strict_types=1);

use App\Service\ItemService;
use Tetthys\DomainKernel\ServiceFailureException;

->calculatePrice(-10);
    echo "Result: {$value}\n";
} catch (ServiceFailureException $e) {
    echo "Failure occurred!\n";
    echo "Reason:  {$e->reason->code()}\n";
    echo "Message: {$e->reason->message()}\n";
    echo "Context: " . json_encode($e->context(), JSON_PRETTY_PRINT) . "\n";
}

src/
  Exceptions/
    ItemFailureReason.php
    ItemFailure.php
  Service/
    ItemService.php
example.php
bash
php example.php