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
    

    No additional configuration needed—auto-discovery handles registration.

  2. First Helper Creation:

    php artisan make:helper StringHelper
    

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

  3. First Usage:

    // Direct global function (automatically available)
    StringHelper::capitalize('hello'); // "Hello"
    

    Or via global function:

    stringHelper()->capitalize('hello');
    

Where to Look First

  • Command: php artisan make:helper (for creating helpers)
  • Directory: app/Helpers/ (where helpers are auto-discovered)
  • Service Provider: L0n3ly\LaravelDynamicHelpers\DynamicHelpersServiceProvider (handles boot-time registration)

First Use Case

Problem: Need reusable string manipulation logic across controllers/Blade. Solution:

php artisan make:helper StringHelper

Add methods to StringHelper:

public function truncate($string, $length = 50)
{
    return Str::limit($string, $length);
}

Use anywhere:

stringHelper()->truncate($longText); // "Shortened text..."

Implementation Patterns

Core Workflows

  1. Helper Creation:

    php artisan make:helper [Nested/]HelperName
    
    • Generates app/Helpers/[Nested/]HelperName.php
    • Supports nested paths (e.g., Store/ProductHelperapp/Helpers/Store/ProductHelper.php)
  2. Access Patterns (Choose One):

    • Global Function: helperName()stringHelper()->method()
    • Static Call: HelperName::method() (via __callStatic)
    • Proxy: helpers()->helperName()->method()
  3. Nested Helper Usage:

    php artisan make:helper Auth/OAuthHelper
    

    Access via camelCase:

    authOAuthHelper()->getProvider();
    

Integration Tips

  • Controllers:
    public function show(Request $request)
    {
        $data = stringHelper()->sanitize($request->input('data'));
        return view('view', ['data' => $data]);
    }
    
  • Blade Templates:
    <h1>{{ stringHelper()->titleCase($post->title) }}</h1>
    
  • Service Providers: Bind helpers to container for dependency injection:
    $this->app->bind('stringHelper', function ($app) {
        return new \App\Helpers\StringHelper();
    });
    

Advanced Patterns

  1. Callable Helpers:

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

    Usage:

    $sum = calculatorHelper(5, 10); // 15
    
  2. Dependency Injection:

    class StringHelper extends Helper
    {
        public function __construct(private Translator $translator) {}
    }
    

    Register binding in AppServiceProvider:

    $this->app->bind(\App\Helpers\StringHelper::class, function ($app) {
        return new \App\Helpers\StringHelper($app->make(Translator::class));
    });
    
  3. Grouped Helpers: Organize helpers by domain (e.g., Auth/, Store/) and use flattened camelCase:

    authOAuthHelper()->login(); // From `app/Helpers/Auth/OAuthHelper.php`
    

Gotchas and Tips

Pitfalls

  1. IDE Autocomplete Delays:

    • Global functions are generated at boot time. Restart your IDE/server if autocompletion doesn’t appear immediately.
    • Fix: Run php artisan optimize:clear and restart your IDE.
  2. Naming Conflicts:

    • Avoid helper names that conflict with Laravel core functions (e.g., userHelper vs. auth()->user()).
    • Tip: Use descriptive names like userManagementHelper.
  3. Singleton Behavior:

    • Helpers are singletons by default. Override __construct() carefully to avoid shared state issues.
    • Workaround: Use dependency injection for stateful helpers.
  4. Dynamic Method Calls:

    • Methods not defined in the helper class will throw BadMethodCallException.
    • Debugging: Verify the helper class exists in app/Helpers/ and the method is spelled correctly.
  5. Nested Helper Paths:

    • Ensure directory structure matches the helper name (e.g., Store/ProductHelper requires app/Helpers/Store/).
    • Error: ClassNotFoundException if directories are missing.

Debugging Tips

  1. Check Registration:

    dd(\L0n3ly\LaravelDynamicHelpers\Facades\Helpers::getHelpers());
    

    Lists all registered helpers.

  2. Verify Boot-Time Generation: Check for generated IDE files in .idea/ or _ide_helper.php after boot.

  3. Clear Cache:

    php artisan optimize:clear
    php artisan config:clear
    

Config Quirks

  • Auto-Discovery: The package scans app/Helpers/ recursively. Exclude files by prefixing with _ (e.g., _BaseHelper.php).
  • Custom Paths: Override the scan path in config/helpers.php (if manually configured):
    'helpers_path' => app_path('CustomHelpers'),
    

Extension Points

  1. Custom Base Class: Extend the base Helper class in app/Providers/AppServiceProvider:

    use L0n3ly\LaravelDynamicHelpers\Helper as BaseHelper;
    
    class CustomHelper extends BaseHelper
    {
        public function __construct()
        {
            // Custom logic
        }
    }
    

    Then update your helpers to extend CustomHelper.

  2. Dynamic Helper Registration: Add custom helpers programmatically in AppServiceProvider@boot():

    use L0n3ly\LaravelDynamicHelpers\Facades\Helpers;
    
    Helpers::addHelper(new \App\Helpers\Custom\DynamicHelper());
    
  3. IDE Helper Customization: Override the generated IDE files by publishing the template:

    php artisan vendor:publish --tag=helpers-ide
    

    Then modify config/helpers.php to point to your custom template.

Performance Tips

  • Avoid Heavy Logic in Constructors: Helpers are instantiated once and reused.
  • Lazy-Load Dependencies: Inject services via constructor or methods to defer initialization.
  • Memoization: Cache expensive operations in helper methods:
    private $cachedData;
    
    public function expensiveOperation()
    {
        return $this->cachedData ??= $this->computeExpensiveData();
    }
    

Laravel-Specific Tips

  • Service Container Binding: Bind helpers to the container for DI:

    $this->app->bind(\App\Helpers\StringHelper::class, function ($app) {
        return new \App\Helpers\StringHelper($app['cache']);
    });
    

    Then resolve via:

    $helper = app(\App\Helpers\StringHelper::class);
    
  • Testing Helpers: Mock helpers in tests using partial mocks:

    $helper = $this->partialMock(\App\Helpers\StringHelper::class, [], [], '', false);
    $this->app->instance(\App\Helpers\StringHelper::class, $helper);
    
  • Helper Facade: Use the Helpers facade for programmatic access:

    use L0n3ly\LaravelDynamicHelpers\Facades\Helpers;
    
    $helper = Helpers::get('stringHelper');
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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