Weave 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

Fluentgen Laravel Package

respect/fluentgen

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require respect/fluentgen
    

    Register the service provider in config/app.php:

    'providers' => [
        Respect\FluentGen\FluentGenServiceProvider::class,
    ],
    
  2. First Use Case Generate a fluent interface for a model (e.g., App\Models\User):

    php artisan fluentgen:generate App\Models\User
    

    This creates a UserFluentInterface.php in app/FluentInterfaces/ with methods like name(), email(), etc.

  3. Where to Look First

    • Artisan Command: php artisan fluentgen:generate (help: php artisan fluentgen:generate --help)
    • Generated Interfaces: Check app/FluentInterfaces/ for auto-generated files.
    • Config: config/fluentgen.php (if provided) for customization.

Implementation Patterns

Usage Patterns

  1. Model Integration Use the generated fluent interface in controllers or services:

    use App\FluentInterfaces\UserFluentInterface;
    
    class UserController {
        public function show(UserFluentInterface $user) {
            return $user->name()->toUpperCase(); // Hypothetical fluent method
        }
    }
    
  2. Dynamic Method Generation Leverage the fluent interface for dynamic queries or method chaining:

    $user = new UserFluentInterface($userModel);
    $result = $user->email()->contains('@')->get();
    
  3. Service Layer Abstraction Wrap Eloquent models in fluent interfaces to enforce consistency:

    class UserService {
        public function __construct(private UserFluentInterface $user) {}
    
        public function getActiveUsers() {
            return $this->user->isActive()->get();
        }
    }
    

Workflows

  1. Generate + Use Cycle

    • Generate interfaces for all models during setup:
      php artisan fluentgen:generate App\Models
      
    • Use interfaces in business logic to enforce fluent syntax.
  2. Testing Mock fluent interfaces in tests:

    $mockUser = $this->createMock(UserFluentInterface::class);
    $mockUser->method('name')->willReturn(new NameFluent($user));
    
  3. IDE Support Enable IDE autocompletion by referencing generated interfaces in PHPDoc blocks:

    /** @var UserFluentInterface */
    $user = resolve(UserFluentInterface::class);
    

Integration Tips

  • Laravel Service Container: Bind fluent interfaces to models for dependency injection:
    $this->app->bind(UserFluentInterface::class, function ($app) {
        return new UserFluentInterface(new User());
    });
    
  • API Resources: Use fluent interfaces in API responses for consistent formatting:
    return new UserResource($user->name()->toUpperCase()->value());
    
  • Form Requests: Validate fluent method chains in form requests:
    public function rules() {
        return [
            'email' => ['required', function ($attribute, $value, $fail) {
                $user = new UserFluentInterface(new User());
                if (!$user->email()->isValid($value)) {
                    $fail('Invalid email format.');
                }
            }]
        ];
    }
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Generated interfaces may clash with existing classes. Prefix namespaces or use unique directory structures (e.g., app/Fluent/).
  2. Dynamic Method Overhead

    • Fluent interfaces add reflection overhead. Avoid overusing for performance-critical paths.
  3. IDE Autocompletion

    • Some IDEs (e.g., PHPStorm) may not auto-detect dynamically generated methods. Use @method PHPDoc annotations:
      /**
       * @method NameFluent name()
       */
      
  4. State Management

    • Fluent interfaces may not track internal state. Ensure methods return new fluent objects:
      // Bad: Mutates state
      $user->name('John')->get(); // Avoid if `name()` modifies $user
      
      // Good: Immutable
      $user->name()->set('John')->get();
      
  5. Testing Edge Cases

    • Test method chaining with invalid inputs:
      $this->expectException(MethodNotAllowedException::class);
      $user->nonExistentMethod()->get();
      

Debugging

  • Generated Code Inspection Check app/FluentInterfaces/ for errors in auto-generated methods. Manually edit if logic is incorrect.

  • Artisan Verbosity Use --verbose for debugging:

    php artisan fluentgen:generate App\Models --verbose
    
  • Reflection Errors If methods aren’t generated, verify:

    • The class exists and is autoloaded.
    • No typos in the namespace/Artisan command.

Config Quirks

  • Custom Directories Override the output directory in config/fluentgen.php (if configurable):

    'output_directory' => app_path('Fluent'),
    
  • Excluded Classes Skip specific classes via config or Artisan flags (if supported):

    php artisan fluentgen:generate App\Models --exclude=App\Models\Admin
    

Extension Points

  1. Custom Method Generators Extend the package by creating a custom generator:

    use Respect\FluentGen\Generators\MethodGeneratorInterface;
    
    class CustomMethodGenerator implements MethodGeneratorInterface {
        public function generateMethods(array $methods) {
            // Add custom logic (e.g., filter methods)
            return array_filter($methods, fn($method) => str_starts_with($method, 'get'));
        }
    }
    
  2. Post-Generation Hooks Use Laravel’s generated:fluent event (if supported) to modify interfaces:

    Event::listen('generated:fluent', function ($interface) {
        $interface->addMethod('customMethod', 'Returns a custom value.');
    });
    
  3. Integration with Laravel Mixins Combine with laravel-mixins for runtime method injection:

    Mixin::make('App\Mixins\UserMixin')->for(UserFluentInterface::class);
    
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums