PHP code example of aldemeery / onion

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

    

aldemeery / onion example snippets


use Aldemeery\Onion\Onion;

$onion = new Onion();

use function Aldemeery\Onion\onion;

$onion = onion();

use Aldemeery\Onion\Onion;
use function Aldemeery\Onion\onion;

// This..
$onion = new Onion([
    fn (string $value): string => strtolower($value),
    // ...
]);

// Is just like this...
$onion = onion(
    fn (string $value): string => strtolower($value),
);

use Aldemeery\Onion\Interfaces\Invokable;
use function Aldemeery\Onion\onion;

class EvenOrOdd implements Invokable
{
    public function __invoke(mixed $passable = null): string
    {
        return (bool) $passable ? 'Even' : 'Odd';
    }
}

$onion = onion([
    fn (int $value): bool => $value % 2 === 0,
    new EvenOrOdd(),
]);

use Aldemeery\Onion\Interfaces\Invokable;
use function Aldemeery\Onion\onion;

class EvenOrOdd implements Invokable
{
    public function __invoke(mixed $passable = null): string
    {
        return (bool) $passable ? 'Even' : 'Odd';
    }
}

$onion = onion([
    fn (int $value): bool => $value % 2 === 0,
    new EvenOrOdd(),
]);

$result = $onion->peel(3); // 'Odd'

use function Aldemeery\Onion\onion;

$onion = onion([
    function (): void {
        // Update a database record...
    },
    function (): void {
        // Send and email...
    }
]);

$onion->peel();

use function Aldemeery\Onion\onion;

$registerUser = onion([
    function (array $data): User {
        return User::create($data);
    },
    function (User $user): User {
        $user->notify(new VerifyEmail());

        return $user;
    },
]);

$user = $registerUser(['name' => 'John Doe', 'email' => '[email protected]']);

use function Aldemeery\Onion\onion;

$onion = onion([
    fn (string $value): string => $value . 'H',
    fn (string $value): string => $value . 'E',
]);

if ($sunIsHot) {
    $onion->add(fn (string $value): string => $value . 'L');
}

$onion->add([
    fn (string $value): string => $value . 'L',
    fn (string $value): string => $value . 'O',
]);

$result = $onion->peel(''); // 'HELLO'

use function Aldemeery\Onion\onion;

$result = onion([
    fn (string $value): string => $value . 'H',
    fn (string $value): string => $value . 'E',
])->addIf(
    $sunIsHot,
    fn (string $value): string => $value . 'L',
)->add([
    fn (string $value): string => $value . 'L',
    fn (string $value): string => $value . 'O',
])->peel(''); // 'HELLO'

use Aldemeery\Onion\Interfaces\Invokable;
use Aldemeery\Onion\Attributes\Layer;
use Illuminate\Http\Request;
use function Aldemeery\Onion\onion;

#[Layer(['name' => 'Authentication Middleware'])]
class Authenticate implements Invokable
{
    public function __invoke(mixed $request = null): Request
    {
        if ($request->user() === null) {
            throw new AuthenticationException();
        }

        return $request;
    }
}

$onion = onion([
    new Authenticate(),
    #[Layer(['name' => 'Log Request Middleware'])]
    function (Request $request): Request {
        log($request);

        return $request;
    }
]);

use function Aldemeery\Onion\onion;

$unlockPremiumFeatures = onion([
    new EnableFeatureOne(),
    new EnableFeatureTwo(),
]);

$unlockSupport = onion([
    new EnableCustomerSupport(),
    new AssignPrivateSupportAgent(),
]);

$registerUser = onion([
    new StoreUserInDatabase(),
    new SendVerificationEmail(),
]);

$registerPremiumUser = onion([
    $registerUser,
    $unlockPremiumFeatures,
    new SendPremiumWelcomeEmail(),
])->addIf($paidForSupport, [
    $unlockSupport,
    new SendSupportCredentialsEmail(),
]);

$data = ['name' => 'John Doe', 'email' => '[email protected]'];

if ($paidForPremium) {
    $registerPremiumUser->peel($data);
} else {
    $registerUser->peel($data);
}

use Aldemeery\Onion\Attributes\Layer;
use Aldemeery\Onion\Exceptions\LayerException;
use Aldemeery\Onion\Onion;

$onion = new Onion([
    #[Layer(['name' => 'division-by-zero', 'description' => 'Attempt to divide by zero'])]
    fn (int $value): float => $value / 0,
]);

try {
    $onion->peel(1);
} catch (LayerException $e) {
    var_dump([
        'passable' => $e->getPassable(),               // Value passed into the layer
        'layer' => $e->getLayer(),                     // Layer that threw the exception
        'layerMetadata' => $e->getLayerMetadata(),     // Full metadata of the layer
        'metadataKey' => $e->getLayerMetadata('name'), // Specific metadata key
        'message' => $e->getMessage(),                 // Exception message
        'previous' => $e->getPrevious(),               // Original exception before conversion
    ]);
}

use Aldemeery\Onion\Exceptions\LayerException;
use Aldemeery\Onion\Onion;

$onion = new Onion([
    fn (int $value): float => $value / 0,
])->withoutExceptionHandling();

try {
    $onion->peel(1);
} catch (DivisionByZeroError $e) {
    $e->getMessage(); // 'Division by zero'
}

use function Aldemeery\Onion\onion;

$onion = onion([
    fn (int $value): float => $value / 0,
]);

$onion->setExceptionHandler(function (Throwable $e, Closure|Invokable $layer, mixed $passable): mixed {
    if ($e instanceof MyCustomException) {
        throw $e; // Allow the exception to propagate
    }

    throw new MyCustomException('This is a custom exception');
});

try {
    $onion->peel(1);
} catch (MyCustomException $e) {
    $e->getMessage(); // 'This is a custom exception'
}

$result = 'Hello World'
    |> htmlentities(...)
    |> str_split(...)
    |> fn($x) => array_map(strtoupper(...), $x)
    |> fn($x) => array_filter($x, fn($v) => $v != 'O');

use function Aldemeery\Onion\onion;

$result = onion([
    htmlentities(...),
    str_split(...),
    fn ($v) => array_map(strtoupper(...), $v),
    fn ($x) => array_filter($x, fn ($v) => $v != 'O'),
])->peel('Hello World');

use League\Pipeline\Pipeline;

$pipeline = (new Pipeline())
    ->pipe(new ConvertToPsr7Request())
    ->pipe(new ExecuteHttpRequest())
    ->pipe(new ParseJsonResponse())
    ->pipe(new ConvertToResponseDto());

$pipeline->process(new DeleteBlogPost($postId));

use function Aldemeery\Onion\onion;

$onion = onion([
    new ConvertToPsr7Request(),
    new ExecuteHttpRequest(),
    new ParseJsonResponse(),
    new ConvertToResponseDto(),
]);

$onion->peel(new DeleteBlogPost($postId));

use App\Models\User;
use Illuminate\Support\Facades\Pipeline;

$user = Pipeline::send($user)
    ->through([
        GenerateProfilePhoto::class,
        ActivateSubscription::class,
        SendWelcomeEmail::class,
    ])
    ->then(fn (User $user) => $user);

use App\Models\User;
use function Aldemeery\Onion\onion;

$user = onion([
    new GenerateProfilePhoto(),
    new ActivateSubscription(),
    new SendWelcomeEmail(),
    fn (User $user): User => $user,
])->peel($user);

use Aldemeery\Onion\Interfaces\Invokable;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use function Aldemeery\Onion\onion;

class AuthenticateRequest implements Invokable, RequestHandlerInterface
{
    public function __invoke(mixed $passable = null): ResponseInterface
    {
        $this->handle($passable);
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // Handle the request...
    }
}

class AuthorizeRequest implements Invokable, RequestHandlerInterface
{
    public function __invoke(mixed $passable = null): ResponseInterface
    {
        $this->handle($passable);
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // Handle the request...
    }
}

class ProcessRequest implements Invokable, RequestHandlerInterface
{
    public function __invoke(mixed $passable = null): ResponseInterface
    {
        $this->handle($passable);
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // Handle the request...
    }
}

class ServerRequest implements ServerRequestInterface
{
    // ...
}

$response = onion([
    new AuthenticateRequest(),
    new AuthorizeRequest(),
    new ProcessRequest(),
])->peel(new ServerRequest());