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

Millwright Util Laravel Package

zerkalica/millwright-util

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require zerkalica/millwright-util
    

    No additional configuration is required for basic usage.

  2. First Use Case: Service Tag Aggregation If using Laravel's service container (which extends Symfony's DI container), leverage ContainerUtil to aggregate services by tag:

    use Zerkalica\MillwrightUtil\ContainerUtil;
    
    // In a service provider or controller
    $aggregatedServices = ContainerUtil::getAggregatedServices($container, 'my.tag');
    
  3. First Use Case: Safe Array Merge Use PhpUtil for safe array merging (avoids overwriting existing keys):

    use Zerkalica\MillwrightUtil\PhpUtil;
    
    $merged = PhpUtil::safeMerge(
        ['key1' => 'value1', 'key2' => 'value2'],
        ['key2' => 'overwritten', 'key3' => 'value3']
    );
    // Result: ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3']
    
  4. First Use Case: SQL Date Formatting Use DateUtil constants for consistent SQL date formatting:

    use Zerkalica\MillwrightUtil\DateUtil;
    
    $formattedDate = (new \DateTime())->format(DateUtil::SQL_DATETIME);
    

Implementation Patterns

Service Container Integration

  1. Tag-Based Service Aggregation Use ContainerUtil::getAggregatedServices() to group services by tags (e.g., for middleware, event listeners, or custom logic):

    // In a service provider
    $this->app->tag(['service1', 'service2'], 'my.tag');
    $services = ContainerUtil::getAggregatedServices($this->app, 'my.tag');
    
  2. Configuration Merging Merge configurations safely (e.g., for environment-specific overrides):

    $baseConfig = require config('base.php');
    $envConfig = require config('env.php');
    $mergedConfig = PhpUtil::safeMerge($baseConfig, $envConfig);
    

Common Workflows

  1. Assertions for Input Validation Use PhpUtil::assert* methods to validate data early:

    PhpUtil::assertArrayHasKey('user_id', $request->all(), 'User ID is required');
    
  2. Safe Cloning of Objects Avoid deep-copy pitfalls with PhpUtil::safeClone():

    $original = new MyClass();
    $clone = PhpUtil::safeClone($original); // Handles circular references
    
  3. Date Handling in Queries Standardize date formats for Eloquent queries:

    $date = (new \DateTime())->format(DateUtil::SQL_DATE);
    User::whereDate('created_at', '=', $date)->get();
    

Laravel-Specific Tips

  • Service Providers: Use ContainerUtil in register() to organize tagged services.
  • Middleware: Tag middleware and aggregate them dynamically:
    $middleware = ContainerUtil::getAggregatedServices($this->app, 'web.middleware');
    
  • Config Publishing: Extend safeMerge for environment-specific config overrides.

Gotchas and Tips

Pitfalls

  1. ContainerUtil Assumptions

    • Assumes Symfony DI container (Laravel’s container works, but standalone Symfony may need adjustments).
    • Fix: Wrap calls in if ($container instanceof ContainerInterface) checks.
  2. PhpUtil::safeMerge Quirks

    • Overwrites arrays at the same depth, not recursively.
    • Workaround: Use array_merge_recursive for nested structures if needed.
  3. DateUtil Constants

    • Constants are static; ensure they match your database’s SQL mode (e.g., SQL_DATETIME may vary by MySQL version).
    • Tip: Add a config option to override defaults:
      config(['millwright.date_format' => DateUtil::SQL_DATETIME]);
      

Debugging

  1. Tagged Services Missing

    • Verify tags are registered before calling getAggregatedServices().
    • Debug: Dump the container’s tags:
      dd($container->findTagged('my.tag'));
      
  2. Safe Merge Unexpected Behavior

    • Use var_dump($merged, $original, $override) to compare inputs/outputs.
    • Tip: Add a debug: true flag to safeMerge for verbose logging.
  3. Circular References in safeClone

    • safeClone may fail silently. Use PhpUtil::isSafeToClone() first:
      if (!PhpUtil::isSafeToClone($object)) {
          throw new \RuntimeException('Object contains circular references');
      }
      

Extension Points

  1. Custom Assertions Extend PhpUtil by adding static methods:

    // In a helper file
    use Zerkalica\MillwrightUtil\PhpUtil;
    
    if (!PhpUtil::assertStringStartsWith($str, 'prefix')) {
        // Handle error
    }
    
  2. New Date Formats Add constants to DateUtil in a trait or subclass:

    trait CustomDateUtil {
        public const CUSTOM_FORMAT = 'Y-m-d H:i:s.u';
    }
    
  3. Container Utilities Extend ContainerUtil for Laravel-specific features (e.g., binding aggregated services):

    $services = ContainerUtil::getAggregatedServices($app, 'my.tag');
    $app->bind('my.tagged.services', fn() => $services);
    

Performance Notes

  • safeMerge: O(n) complexity; avoid in tight loops for large arrays.
  • safeClone: Uses serialization; test with large objects for memory impact.
  • Tag Aggregation: Cache results if called frequently:
    $this->app->singleton('cached.tagged.services', fn() =>
        ContainerUtil::getAggregatedServices($this->app, 'my.tag')
    );
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata