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

Macroable Laravel Package

wp-starter/macroable

Lightweight Macroable trait for PHP/Laravel-style macros. Add runtime methods to your classes, register macros and mixins, and call them like native methods—useful for extending objects without inheritance or boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require wp-starter/macroable
    

    Add to composer.json under "extra":

    "laravel": {
        "macroable": true
    }
    
  2. First Use Case: Extend a Laravel model (e.g., User) with a custom macro:

    use WPStarter\Macroable\Macroable;
    
    class User extends Authenticatable
    {
        use Macroable;
    }
    
    // Register a macro (e.g., in a service provider)
    User::macro('fullName', function () {
        return "{$this->first_name} {$this->last_name}";
    });
    
    // Usage:
    $user = User::first();
    echo $user->fullName(); // Outputs: "John Doe"
    
  3. Key Files:

    • config/macroable.php (if published): Defaults and global settings.
    • app/Providers/MacroServiceProvider.php: Register macros here (or use boot() in AppServiceProvider).

Implementation Patterns

Core Workflows

  1. Model Macros:

    • Dynamic Methods: Add reusable logic to models without inheritance.
      // In a service provider
      User::macro('isAdmin', function () {
          return $this->role === 'admin';
      });
      
      // Usage
      if ($user->isAdmin()) { ... }
      
    • Collection Macros: Extend Eloquent collections:
      User::macro('activeOnly', function () {
          return $this->where('active', true);
      });
      
  2. Service/Helper Macros:

    • Extend Laravel’s built-in classes (e.g., Request, Response):
      \Illuminate\Http\Request::macro('getIp', function () {
          return $this->ip() ?? $this->header('X-Forwarded-For');
      });
      
  3. Conditional Macros:

    • Use when() to conditionally register macros:
      if (config('app.env') === 'local') {
          User::macro('debug', function () {
              return $this->toArray();
          });
      }
      
  4. Macro Groups:

    • Organize macros by feature (e.g., User::macroGroup('permissions', ...)) or use traits to group logic.

Integration Tips

  • Service Providers: Centralize macro registration in MacroServiceProvider for clarity.
  • Testing: Mock macros in tests:
    User::macro('testMacro', fn() => 'mocked');
    $this->assertEquals('mocked', User::first()->testMacro());
    
  • Documentation: Use PHPDoc for macros to enable IDE autocompletion:
    /**
     * @return string
     */
    User::macro('fullName', function () { ... });
    

Gotchas and Tips

Pitfalls

  1. Macro Overwriting:

    • Macros can be overwritten if registered multiple times. Use hasMacro() to check:
      if (!User::hasMacro('fullName')) {
          User::macro('fullName', ...);
      }
      
  2. Late Static Binding:

    • Macros rely on static calls. Avoid dynamic class names (e.g., $className::macro()) unless using call_user_func().
  3. Performance:

    • Macros add minimal overhead, but avoid heavy computations in frequently called macros.
    • Cache macro definitions if registering many dynamically.
  4. Namespace Collisions:

    • Ensure macro names are unique across the application (e.g., User::macro('scopeActive', ...) vs. Model::macro('scopeActive', ...)).

Debugging

  • Macro Not Found:

    • Verify the macro is registered before first use (e.g., in a service provider’s boot()).
    • Check for typos in macro names (Laravel is case-sensitive).
  • Macro Not Working:

    • Use dd(\WPStarter\Macroable\Macroable::getMacros(User::class)) to list registered macros.
    • Ensure the class using the macro has the Macroable trait.

Extension Points

  1. Custom Macro Storage: Override the default storage (e.g., cache macros in a database for shared hosting):

    \WPStarter\Macroable\Macroable::setStorage(new DatabaseMacroStore());
    
  2. Macro Events: Listen for macro registration/unregistration via events (if the package supports it; extend if needed):

    event(new MacroRegistered(User::class, 'fullName'));
    
  3. Dynamic Macro Loading: Load macros from config or files:

    $macros = config('macroable.user');
    foreach ($macros as $name => $callback) {
        User::macro($name, $callback);
    }
    

Config Quirks

  • Publish Config:

    php artisan vendor:publish --tag=macroable-config
    
    • Adjust macroable.php to:
      • Enable/disable global macro registration.
      • Set default macro storage (e.g., cache, database).
      • Whitelist/blacklist classes for macro support.
  • Environment-Specific Macros: Use config to load environment-specific macros:

    config(['macroable.macros.' . config('app.env') => [...]]);
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle