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 Stub Laravel Package

binafy/laravel-stub

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require binafy/laravel-stub
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="Binafy\Stub\StubServiceProvider"
    
  2. First Use Case: Generate a basic stub file (e.g., UserController.stub) in resources/stubs/ and publish it to app/Http/Controllers/UserController.php:

    use Binafy\Stub\Facades\Stub;
    
    Stub::create('UserController.stub')
        ->to(app_path('Http/Controllers/UserController.php'))
        ->moveStub();
    

Where to Look First

  • Stub Directory: Default location is resources/stubs/. Check the stub config for custom paths.
  • Facade: Use Binafy\Stub\Facades\Stub for fluent stub generation.
  • CLI Artisan Command: Run php artisan stub:create for interactive stub creation.

Implementation Patterns

Core Workflows

  1. Stub Generation Pipeline:

    Stub::create('stub-name.stub')
        ->to('destination/path.php') // Required
        ->name('CustomName')         // Optional: Rename output file
        ->ext('php')                // Optional: Force extension
        ->replace(['old' => 'new']) // Replace placeholders
        ->replaces(['old' => 'new']) // Replace in stub file (pre-processing)
        ->conditions(['key' => 'value']) // Conditional logic
        ->moveStub();               // Execute
    
  2. Dynamic Stubs with Conditions: Use conditions() to branch logic (e.g., generate different stubs for Model vs Controller):

    Stub::create('Base.stub')
        ->conditions(['type' => 'Model'])
        ->replace(['{{namespace}}' => 'App\Models'])
        ->moveStub();
    
  3. Stub Templates for Teams: Store reusable stubs in resources/stubs/ and version-control them. Example:

    resources/stubs/
    ├── controllers/
    │   ├── BaseController.stub
    │   └── ApiController.stub
    └── migrations/
        └── BaseMigration.stub
    
  4. Integration with Artisan Commands: Extend Laravel’s scaffolding (e.g., make:controller) by hooking into Stub:

    // app/Console/Commands/MakeCustomController.php
    public function handle()
    {
        Stub::create('ApiController.stub')
            ->to($this->getPath())
            ->replace(['DummyNamespace' => $this->rootNamespace])
            ->moveStub();
    }
    
  5. Stub Preprocessing: Use replaces() to modify stubs before rendering (e.g., inject auth scaffolding):

    Stub::create('AuthController.stub')
        ->replaces([
            '{{uses}}' => 'use App\Models\User;',
            '{{middleware}}' => '@auth',
        ])
        ->moveStub();
    

Integration Tips

  • Laravel IDE Helper: Pair with barryvdh/laravel-ide-helper to auto-generate stubs for IDE hints.
  • Laravel Mix: Use stubs to generate webpack.mix.js configurations dynamically.
  • Testing: Mock stubs in tests with Stub::fake() (if supported) or temporary stub files.

Gotchas and Tips

Pitfalls

  1. Stub File Encoding: Ensure stub files use UTF-8 encoding to avoid encoding issues with special characters (e.g., ©, ).

  2. Placeholder Conflicts: Avoid overlapping placeholders (e.g., {{name}} vs {{namespace}}). Use unique prefixes like {{controller.name}}.

  3. File Overwrites: moveStub() overwrites files silently. Use --force flag in CLI or check file existence first:

    if (!file_exists($destination)) {
        Stub::create('stub.stub')->to($destination)->moveStub();
    }
    
  4. Path Resolution: Relative paths in to() are resolved from the current working directory, not the project root. Use absolute paths or base_path():

    ->to(base_path('app/Http/Controllers/UserController.php'))
    
  5. Conditions Logic: Conditions use array_key_exists() internally. Empty arrays or null values may cause unexpected behavior:

    // Avoid:
    ->conditions(['key' => null])
    // Use:
    ->conditions(['key' => 'value'])
    

Debugging

  1. Dry Run: Use ->dump() to preview the final stub content before writing:

    Stub::create('stub.stub')->to('path.php')->dump();
    
  2. Stub Path Issues: Verify the stubs path in config/stub.php:

    'paths' => [
        resource_path('stubs'),
        // Add custom paths here
    ],
    
  3. Placeholder Errors: Check for unclosed placeholders (e.g., {{name without }}). Use replaces() to validate:

    ->replaces(['{{missing' => 'default']) // Will throw an error
    

Extension Points

  1. Custom Stub Providers: Register additional stub paths in the StubServiceProvider:

    public function register()
    {
        $this->app->singleton('stub', function () {
            $stub = new StubManager();
            $stub->addPath(base_path('custom/stubs'));
            return $stub;
        });
    }
    
  2. Stub Events: Listen for stub generation events (if the package supports them) or wrap Stub calls in a service:

    event(new StubGenerated($destination, $stubContent));
    
  3. Stub Validation: Add pre-flight checks (e.g., validate stub syntax with a regex):

    if (!preg_match('/{{.*}}/', file_get_contents($stubPath))) {
        throw new \Exception('Stub must contain placeholders.');
    }
    
  4. Stub Caching: Cache compiled stubs for performance (e.g., in a StubCompiler class):

    $cacheKey = md5($stubContent);
    if (cache()->has("stub.$cacheKey")) {
        return cache()->get("stub.$cacheKey");
    }
    
  5. Stub Testing: Test stubs in PHPUnit by mocking the Stub facade:

    Stub::shouldReceive('create')
        ->once()
        ->with('test.stub')
        ->andReturnSelf();
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle