edykim/laravel-container-helper

A simple helper for Laravel service container

v0.0.2 2023-07-24 03:06 UTC

This package is auto-updated.

Last update: 2024-11-24 06:04:20 UTC


README

Latest Stable Version License PHP Version Require

This package provides a simple helper for Laravel Container. It allows you to generate an inline utility class that implements a given interface, making your application's logic more configurable.

Getting Started

Installation

$ composer require edykim/laravel-container-helper

Lazy

This function offers a lazy-loaded proxy instance of a given concrete implementation for lazy instantiation.

use function Edykim\LaravelContainerHelper\Support\instance;

// ...
$app->bind(
  CalculatorInterface::class,
  instance(CalculatorInterface::class)
    ->lazy(HeavilyLoadedCalculator::class)
);

Sequence

use function Edykim\LaravelContainerHelper\Support\instance;

// ...
$app->bind(
  CalculatorInterface::class,
  instance(CalculatorInterface::class)
    ->sequence(
      SimpleProductCalculator::class,
      DigitalProductCalculator::class,
      ShippingChargeCalculator::class,
    )
);

Conditional

class HasDigitalProducts {
  public function check(Cart $cart): bool {
    // ...
  }
}
use function Edykim\LaravelContainerHelper\Support\instance;

// ...
$app->bind(
  CalculatorInterface::class,
  instance(CalculatorInterface::class)
    ->when(
      HasDigitalProduct::class,
      DigitalProductCalculator::class,
      SimpleProductCalculator::class,
    )
);

Nested

use function Edykim\LaravelContainerHelper\Support\instance;
use Edykim\LaravelContainerHelper\Support\Instance;

// ...
$app->bind(
  CalculatorInterface::class,
  instance(CalculatorInterface::class)
    ->with(fn (Instance $instance) => 
      $instance->sequence(
        $instance->lazy(
          $instance->when(
            HasCouponWithThirdPartyCompany::class,
            ThirdPartyCouponCalculator::class,
            NothingCalculator::class,
          ),
        ),
        SimpleProductCalculator::class,
        DigitalProductCalculator::class,
        $instance->when(
          [IsPlusLevelCustomer::class, 'validate'],
          PlusLevelCustomerDiscountCalculator::class,
          $instance->when(
            [IsMedicalProvider::class, 'validate'],
            MedicalProviderDiscountCalculator::class,
            NothingCalculator::class,
          ),
        ),
      ),
    );
);