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

Laravel Dynamic Helpers Laravel Package

l0n3ly/laravel-dynamic-helpers

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require l0n3ly/laravel-dynamic-helpers
    

    The package auto-discovers and registers its service provider.

  2. Create your first helper:

    php artisan make:helper MoneyHelper
    

    This generates app/Helpers/MoneyHelper.php with a base Helper class.

  3. Use immediately:

    moneyHelper()->format(1000); // "1,000.00"
    

    No manual registration needed—global functions are auto-generated at boot.

First Use Case

Scenario: Need reusable logic for formatting monetary values across controllers and Blade templates. Solution:

php artisan make:helper MoneyHelper

Edit the generated file:

class MoneyHelper extends Helper {
    public function format($amount) {
        return number_format($amount, 2);
    }
}

Now use anywhere:

// Controller
$formatted = moneyHelper()->format($order->amount);

// Blade
{{ moneyHelper()->format($product->price) }}

Implementation Patterns

Core Workflows

1. Helper Creation & Organization

  • Basic helpers:

    php artisan make:helper StringHelper
    

    Creates app/Helpers/StringHelper.php.

  • Nested helpers (for domain separation):

    php artisan make:helper Store/ProductHelper
    

    Creates app/Helpers/Store/ProductHelper.php and auto-generates storeProductHelper() global function.

  • Access patterns:

    // Global function (preferred)
    storeProductHelper()->getById(1);
    
    // Static call
    StoreProductHelper::getById(1);
    
    // Proxy method
    helpers()->storeProductHelper()->getById(1);
    

2. Integration with Laravel Components

  • Service Providers: Inject helpers via constructor:

    public function __construct(private MoneyHelper $moneyHelper) {}
    

    Laravel’s DI resolves the singleton instance automatically.

  • Blade Directives: Create custom directives using helpers:

    Blade::directive('currency', function ($amount) {
        return "<?php echo moneyHelper()->format($amount); ?>";
    });
    

    Usage:

    @currency($product->price)
    
  • Form Requests: Validate using helper logic:

    public function rules() {
        return [
            'amount' => ['required', Rule::function(fn ($attr, $value) =>
                moneyHelper()->isValidAmount($value)
            )],
        ];
    }
    

3. Testing Helpers

  • Unit Tests: Mock helpers in tests:

    $this->app->instance(MoneyHelper::class, Mockery::mock(MoneyHelper::class));
    

    Or use the global function:

    $helper = $this->app->make(MoneyHelper::class);
    $this->assertEquals('1,000.00', $helper->format(1000));
    
  • Feature Tests: Test Blade/Controller interactions:

    $response = $this->get('/orders');
    $response->assertSee('1,234.56'); // Formatted by moneyHelper()
    

4. Performance Optimization

  • Singleton Caching: Helpers are auto-cached as singletons. Avoid recreating instances:

    // Good
    $helper = moneyHelper();
    
    // Bad (creates new instance)
    $helper = new MoneyHelper();
    
  • Lazy-Loading: Helpers are only instantiated when first called, reducing boot time overhead.

5. Advanced Patterns

  • Callable Helpers:

    class CalculatorHelper extends Helper {
        public function __invoke($a, $b) {
            return $a + $b;
        }
    }
    

    Usage:

    $result = calculatorHelper(5, 10); // 15
    
  • Helper Composition: Combine helpers in a single class:

    class OrderHelper extends Helper {
        public function calculateTotal(Order $order) {
            return moneyHelper()->format(
                $order->items->sum(fn ($item) => $item->price * $item->quantity)
            );
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts:

    • Avoid naming helpers that conflict with Laravel core functions (e.g., authHelper).
    • Fix: Use descriptive names like authenticationHelper.
  2. IDE Autocomplete Delays:

    • If IDE hints are slow, regenerate IDE files manually:
      php artisan helpers:ide
      
    • Tip: Exclude generated _ide_helper.php from version control (it’s auto-generated).
  3. Helper Overwriting:

    • Accidentally overwriting app/Helpers/Helper.php breaks the base class.
    • Fix: Never modify the auto-generated Helper base class in app/Helpers/.
  4. Case Sensitivity in Nested Helpers:

    • Store/ProductHelper generates storeProductHelper(), not store_product_helper().
    • Tip: Stick to PascalCase for helper names to avoid surprises.
  5. Dynamic Function Registration:

    • Global functions are created at boot via eval(). Avoid modifying them directly.
    • Debugging: Check bootstrap/cache/ for generated function files if helpers aren’t available.

Debugging Tips

  • Helper Not Found?:

    • Verify the helper class exists in app/Helpers/ (case-sensitive).
    • Check for typos in the global function name (e.g., moneyHelper vs. MoneyHelper).
  • IDE Not Recognizing Helpers:

    • Run php artisan helpers:ide to regenerate IDE files.
    • For PhpStorm, ensure .phpstorm.meta.php is loaded (check Settings > PHP > Include Paths).
  • Performance Issues:

    • Use tideways/xhprof to profile helper instantiation if boot time is slow.
    • Tip: Helpers are cached, so repeated calls are fast.

Configuration Quirks

  1. Custom Helper Directory:

    • To change the default app/Helpers/ directory, publish the config:
      php artisan vendor:publish --tag=dynamic-helpers-config
      
    • Modify config/dynamic-helpers.php:
      'helpers_path' => app_path('CustomHelpers'),
      
  2. Excluding Helpers:

    • Skip auto-registration for specific helpers by adding them to config/dynamic-helpers.php:
      'excluded_helpers' => [
          'App\Helpers\Legacy\OldHelper',
      ],
      
  3. Boot Order:

    • Helpers are registered after service providers boot. If a helper depends on a provider (e.g., auth), ensure the provider boots first.

Extension Points

  1. Custom Base Helper:

    • Extend the base Helper class by publishing the stub:
      php artisan vendor:publish --tag=dynamic-helpers-stubs
      
    • Modify stubs/helper.stub to add default methods or traits.
  2. Dynamic Helper Registration:

    • Override the boot method in your service provider:
      public function boot() {
          $this->app->registerDynamicHelpers([
              'App\Helpers\Custom\NamespaceHelper',
          ]);
      }
      
  3. IDE File Customization:

    • Extend the IDE helper generator by binding a custom generator:
      $this->app->bind(IdeHelperGenerator::class, CustomIdeHelperGenerator::class);
      
  4. Helper Events:

    • Listen for helper registration events:
      event(new HelpersRegistered($helpers));
      
    • Publish the event class:
      php artisan vendor:publish --tag=dynamic-helpers-events
      

Pro Tips

  • Helper Naming Conventions: Use PascalCase for helper classes and camelCase for global functions:

    • MoneyHelpermoneyHelper()
    • Store/ProductHelperstoreProductHelper()
  • Documentation: Add PHPDoc blocks to helpers for better IDE support:

    /**
     * Formats an amount as currency.
     *
     * @param float $amount
     * @return string
     */
    public function format($amount) { ... }
    
  • Testing Helpers: Use the helpers() proxy in tests for better isolation:

    $this->app->instance(MoneyHelper::class, Mockery::mock());
    helpers()->moneyHelper()->shouldReceive('format')->andReturn('100.00');
    
  • Laravel Boost Integration: Leverage AI-powered helper scaffolding:

    php artisan boost:skill:install l0n3ly/laravel-dynamic-helpers
    

    Then use Boost to generate helpers with natural language:

    php artisan boost:generate "create a helper for formatting dates"
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor