Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Foundation Laravel Package

php-standard-library/foundation

A lightweight PHP foundation library offering common building blocks and utilities to bootstrap projects. Provides reusable helpers and core abstractions to reduce boilerplate and standardize patterns across apps and packages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require php-standard-library/foundation
    

    Add to composer.json under require or require-dev if only for testing.

  2. First Use Case: Replace a custom exception or utility with the package’s equivalents. Example:

    use Foundation\Exceptions\InvalidArgumentException;
    use Foundation\Ref\Ref;
    
    // Replace custom validation logic
    if (!is_string($input)) {
        throw new InvalidArgumentException('Input must be a string');
    }
    
    // Use Ref for immutable references (alternative to Laravel's helpers)
    $ref = Ref::of($value);
    $ref->set(fn($v) => strtolower($v));
    
  3. Where to Look First:

    • Exceptions: Foundation\Exceptions for standardized error handling.
    • Ref: Foundation\Ref for immutable references and functional operations.
    • Invariants: Foundation\Invariant for runtime assertions (e.g., preconditions).
    • Documentation: PHP Standard Library Docs (if available).

Implementation Patterns

Usage Patterns

  1. Exception Handling:

    • Replace Laravel’s Illuminate\Support\MessageBag or custom exceptions with Foundation\Exceptions\*.
    • Example:
      use Foundation\Exceptions\NotFoundException;
      
      if (!$user = User::find($id)) {
          throw new NotFoundException("User with ID {$id} not found");
      }
      
  2. Immutable References (Ref):

    • Use Ref for functional programming patterns (e.g., chaining operations).
    • Example:
      use Foundation\Ref\Ref;
      
      $result = Ref::of($data)
          ->map(fn($item) => strtolower($item))
          ->filter(fn($item) => strlen($item) > 3)
          ->toArray();
      
  3. Invariants:

    • Enforce preconditions/postconditions in methods.
    • Example:
      use Foundation\Invariant\Invariant;
      
      public function process(array $data): void {
          Invariant::that($data)->isNotEmpty()->isArray();
          // ...
      }
      
  4. Integration with Laravel:

    • Service Container: Bind package interfaces to Laravel’s contracts.
      $this->app->bind(
          Foundation\LoggerInterface::class,
          Illuminate\Contracts\Logging\Logger::class
      );
      
    • Middleware: Use Ref for request/response transformations.
      public function handle($request, Closure $next) {
          $response = $next($request);
          return Ref::of($response)
              ->tap(fn($r) => $r->header('X-Processed', 'true'))
              ->toResponse();
      }
      
  5. Testing:

    • Mock package classes in PHPUnit/Pest.
    • Example:
      $this->mock(Foundation\LoggerInterface::class)
          ->shouldReceive('error')
          ->once();
      

Workflows

  1. Modular Migration:

    • Start with a single module (e.g., API responses) and replace custom utilities.
    • Example: Replace App\Helpers\ArrayHelper with Foundation\ArrayHelper.
  2. Domain-Driven Design (DDD):

    • Use Result types (if available) for domain logic.
    • Example:
      use Foundation\Result\Result;
      
      public function createOrder(OrderData $data): Result {
          return Result::try(fn() => Order::create($data->toArray()));
      }
      
  3. Event Handling:

    • Extend package classes to emit Laravel events.
    • Example:
      use Foundation\Exceptions\Exception;
      use Illuminate\Support\Facades\Event;
      
      class CustomException extends Exception {
          public function __construct(string $message) {
              parent::__construct($message);
              Event::dispatch(new ExceptionOccurred($this));
          }
      }
      

Integration Tips

  • Avoid Overlap: Skip Laravel-specific features (e.g., use Illuminate\Support\Collection instead of Foundation\Collection).
  • Namespace Aliases: Add to composer.json to shorten imports:
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Foundation\\": "vendor/php-standard-library/foundation/src"
        }
    }
    
  • Custom Extensions: Create a FoundationExtensions package for Laravel-specific adaptations.

Gotchas and Tips

Pitfalls

  1. Framework Assumptions:

    • The package may not account for Laravel’s service container, facades, or helpers. Example: Foundation\Str might lack Laravel’s Str::of() behavior.
    • Fix: Extend or wrap package classes to bridge gaps.
  2. Performance Overhead:

    • Functional patterns (e.g., Ref) can introduce closure overhead in tight loops.
    • Fix: Benchmark critical paths; use native PHP where performance matters.
  3. Naming Conflicts:

    • Classes like Foundation\Array might conflict with Laravel’s Illuminate\Support\Arr.
    • Fix: Use fully qualified namespaces or aliases.
  4. Testing Quirks:

    • Package classes may not be designed for Laravel’s mocking or testing helpers.
    • Fix: Use partialMock or interface-based mocks.
  5. Dependency Bloat:

    • The package might pull in unnecessary Symfony components (check composer why-not).
    • Fix: Fork or use a subset of classes.

Debugging

  • Stack Traces: Package exceptions may not integrate with Laravel’s debugbar or error pages.
    • Fix: Extend exceptions to include Laravel-specific context:
      class LaravelException extends Foundation\Exceptions\Exception {
          public function render(): Response {
              return response()->json(['error' => $this->getMessage()], 400);
          }
      }
      
  • Invariant Failures: Assertions throw Foundation\Invariant\ViolationException. Catch and log with Laravel’s report():
    try {
        Invariant::that($value)->isNotNull();
    } catch (ViolationException $e) {
        report($e);
        abort(400, $e->getMessage());
    }
    

Config Quirks

  • No Laravel Config: The package lacks config/foundation.php. Use environment variables or a custom config file:
    // config/foundation.php
    return [
        'default_locale' => env('FOUNDATION_LOCALE', 'en_US'),
    ];
    
  • Service Provider: Register package bindings in AppServiceProvider:
    public function register() {
        $this->app->singleton(Foundation\LoggerInterface::class, function ($app) {
            return new Foundation\Logger($app['log']);
        });
    }
    

Extension Points

  1. Custom Exceptions:

    • Extend Foundation\Exceptions\Exception for Laravel-specific behavior:
      class HttpException extends Foundation\Exceptions\Exception {
          public function __construct(string $message, int $status = 400) {
              parent::__construct($message);
              $this->status = $status;
          }
      
          public function toResponse(): Response {
              return response()->json(['error' => $this->message], $this->status);
          }
      }
      
  2. Ref Monads:

    • Add Laravel-specific operations to Ref:
      Ref::extend('laravel', function ($ref) {
          return $ref->tap(fn($value) => Log::debug('Ref value:', $value));
      });
      
  3. Invariant Rules:

    • Create custom rules for Laravel validation:
      use Foundation\Invariant\Rule;
      
      class LaravelRule extends Rule {
          public static function isValidatedBy(string $validator): self {
              return new static(fn($value) => validator($value)->validate());
          }
      }
      

Pro Tips

  • Hybrid Approach: Use the package for cross-cutting concerns (e.g., logging, validation) but keep Laravel’s helpers for framework-specific tasks.
  • Document Conventions: Add a CONTRIBUTING.md to your repo outlining how to use the package (e.g., "Always use Foundation\Result for domain operations").
  • Performance: For collections, compare Foundation\Collection vs. Laravel’s Illuminate\Support\Collection in benchmarks.
  • Fallbacks: Provide fallback implementations for unsupported PHP versions:
    if (!function_exists('Foundation\Ref\Ref::of')) {
        function Ref_of($value) { /* fallback */ }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium